Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≤ x ≤ b and x is divisible by k.

The only line contains three space-separated integers k, a and b (1 ≤ k ≤ 1018; - 1018 ≤ a ≤ b ≤ 1018).

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | k > abs (a) && k > abs (b) && a <= 0 && b >= 0 = 1
  | combo1 == 0 && combo2 == 0 = abs (result)
  | k > abs (a) && combo1 /= 0 = divisibility k k b
  | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b
  | k > abs (b) && combo2 /= 0 = divisibility k a 0
  | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

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

check [k, a, b] = b `quot` k - a `quot` k +
    if max a (-b) `mod` k == 0 || b - a > abs (a + b)
            then 1 else 0

import Data.Int

main = getLine >>= print . solve . map (read :: String -> Int64) . words

solve [k, a, b]
  | a == 0 = b `div` k + 1
  | 0 < a =  solve [k, 0, b] - solve [k, 0, a - 1]
  | a < 0 && 0 < b = solve [k, 0, -a] + solve [k, 0, b] - 1
  | otherwise = solve [k, -b, -a]

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | mod (abs a) k /= 0 && mod (abs b) k /= 0 = result
   | otherwise = 1 + result
   where l = 10^18
         result = round $ fromInteger (b - a) / fromInteger k

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | mod (abs a) k /= 0 && mod (abs b) k /= 0 = result
   | otherwise = 1 + result
   where l = 10^18
         result = div (b - a) k

main :: IO ()
main = do
       args <- getLine
       result <- return $ show $ divisibility (read (head $ split args) :: Int)
                                           (read (secd $ split args) :: Int)
                                           (read (last $ split args) :: Int)
       putStrLn result

divisibility k a b = sum [1 | k > 0, a <= l, a >= s, b <= l, b >= s, a <= b,
                              xs <- [a..b], mod xs k == 0]
                     where l = 10^18
                           s = -1*l

split' :: Eq a => a -> [a] -> [[a]]
split' d [] = []
split' d s = x : split' d (drop 1 y) where (x,y) = span (/= d) s

split = split' ' '
secd = head . tail

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | k > abs (a) && k > abs (b) = 1
  | combo1 == 0 && combo2 == 0 = result
  | k > abs (a) && combo1 /= 0 = divisibility k k b
  | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b
  | k > abs (b) && combo2 /= 0 = divisibility k a 0
  | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | k > abs (a) && k > abs (b) && a < 0 && b > 0 = 1
  | combo1 == 0 && combo2 == 0 = abs (result)
  | k > abs (a) && combo1 /= 0 = divisibility k k b
  | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b
  | k > abs (b) && combo2 /= 0 = divisibility k a 0
  | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
       args <- getLine
       result <- return $ show $ divisibility (read (head $ split args) :: Int)
                                              (read (secd $ split args) :: Int)
                                              (read (last $ split args) :: Int)
       putStr result

divisibility k a b = sum [1 | k > 0, a <= l, a >= s, b <= l, b >= s, a <= b,
                              xs <- [a..b], mod xs k == 0]
                     where l = 10^18
                           s = -1*l

split' :: Eq a => a -> [a] -> [[a]]
split' d [] = []
split' d s = x : split' d (drop 1 y) where (x,y) = span (/= d) s

split = split' ' '
secd = head . tail

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ floor $ divisibility arg1 arg2 arg3

divisibility k a b
  | combo1 == 0 && combo2 == 0 = fromIntegral (b - a + k) / fromIntegral k
  | combo1 /= 0 = divisibility k (a + 1) b
  | otherwise = divisibility k a (b - 1)
  where combo1 = mod a k
        combo2 = mod b k

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | k > a || k > b || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | combo1 == 0 && combo2 == 0 = result
  | combo1 /= 0 = divisibility k (a + 1) b
  | combo1 == 0 = divisibility k a (b - 1)
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | mod (abs a) k /= 0 && mod (abs a) k /= 0 = result
   | otherwise = 1 + result
   where l = 10^18
         result = div (b - a) k

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | (abs a < k || abs b < k) && a /= 0 && b /= 0  = result
   | otherwise = 1 + result
   where l = 10^18
         result = div (b - a) k

main :: IO Int
main = do
     args <- getLine
     return $ divisibility (read (head (split ' ' args)) :: Int)
                           (read (head $ tail (split ' ' args)) :: Int)
                           (read (last (split ' ' args)) :: Int)

divisibility k a b = sum [1 | k > 0, a <= l, a >= s, b <= l, b >= s, a <= b,
                              xs <- [a..b], mod xs k == 0]
                     where l = 10^18
                           s = -1*l

split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b = (b - a + 1) / k

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | k > abs (a) && k > abs (b) = 1
  | combo1 == 0 && combo2 == 0 = abs (result)
  | k > abs (a) = divisibility k k b
  | k < abs (a) = divisibility k (a - combo1 + k) b
  | k > abs (b) = divisibility k a 0
  | k < abs (b) = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | k > abs (a) && k > abs (b) = 1
  | combo1 == 0 && combo2 == 0 = result
  | k > abs (a) = divisibility k k b
  | k < abs (a) = divisibility k (a - combo1 + k) b
  | k > abs (b) = divisibility k a 0
  | k < abs (b) = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
     args <- getLine
     print $ divisibility (read (head (split ' ' args)) :: Int)
                           (read (head $ tail (split ' ' args)) :: Int)
                           (read (last (split ' ' args)) :: Int)

divisibility k a b = sum [1 | k > 0, a <= l, a >= s, b <= l, b >= s, a <= b,
                              xs <- [a..b], mod xs k == 0]
                     where l = 10^18
                           s = -1*l

split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | abs a < k && abs b < k && a /= 0 && b /= 0  = result
   | otherwise = 1 + result
   where l = 10^18
         result = div (b - a) k

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | (k > abs (a) && k > abs (b)) || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | a == 0 && b == 0 = 1
  | combo1 == 0 && combo2 == 0 = result
  | k > abs (a) = divisibility k k b
  | k < abs (a) = divisibility k (a - combo1 + k) b
  | k > abs (b) = divisibility k a 0
  | k < abs (b) = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility :: Int -> Int -> Int -> Int
divisibility 1 a b = b - a + 1
divisibility k a b = length [x | x <- [a..b], mod x k == 0]

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility 1 a b = b - a + 1
divisibility k a b = length [x | x <- [a..b], mod x k == 0]

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | (k > abs (a) && k > abs (b)) || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | a == 0 && b == 0 = 0
  | combo1 == 0 && combo2 == 0 = result
  | k > abs (a) = divisibility k k b
  | k < abs (a) = divisibility k (a - combo1 + k) b
  | k > abs (b) = divisibility k a 0
  | k < abs (b) = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | abs a < k || abs b < k = result
   | otherwise = 1 + result
   where l = 10^18
         result = div (b - a) k

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | k > abs (a) && k > abs (b) && a < 0 = 1
  | combo1 == 0 && combo2 == 0 = abs (result)
  | k > abs (a) && combo1 /= 0 = divisibility k k b
  | k < abs (a) && combo1 /= 0 = divisibility k (a - combo1 + k) b
  | k > abs (b) && combo2 /= 0 = divisibility k a 0
  | k < abs (b) && combo2 /= 0 = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k 0 0 = 0
divisibility k a b
  | (k > abs (a) && k > abs (b)) || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | combo1 == 0 && combo2 == 0 = result
  | k > abs (a) = divisibility k k b
  | k < abs (a) = divisibility k (a - combo1 + k) b
  | k > abs (b) = divisibility k a 0
  | k < abs (b) = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | mod (abs b) k /= 0 = result
   | otherwise = 1 + result
   where l = 10^18
         result = div (b - a) k

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | (mod (abs a) k == 0) || mod (abs b) k == 0 = 1 + result
   | otherwise = result
   where l = 10^18
         result = div (b - a) k

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility2 arg1 arg2 arg3

divisibility2 k a b
   | k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
   | otherwise = 1 + div (b - a) k
   where l = 10^18

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

check [k, a, b] = b `div` k - a `div` k +
    if min a b `mod` k == 0 || b - a > abs (a + b)
            then 1 else 0

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

check [k, a, b] = segment `div` k +
    if min a b `mod` k == 0 || segment > abs (a + b)
            then 1
            else 0
    where segment = b - a

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

check [k, a, b] = b `quot` k - a `quot` k +
    if min a b `mod` k == 0 || b - a > abs (a + b)
            then 1 else 0

main :: IO ()
main = do
       argsStr <- getLine
       let [arg1, arg2, arg3] = map read $ words argsStr
       print $ divisibility arg1 arg2 arg3

divisibility k a b
  | (k > abs (a) && k > abs (b)) || k < 0 || k > l || a < (-1)*l || a > l || b < (-1)*l || b > l = 0
  | combo1 == 0 && combo2 == 0 = result
  | k > abs (a) = divisibility k k b
  | k < abs (a) = divisibility k (a - combo1 + k) b
  | k > abs (b) = divisibility k a 0
  | k < abs (b) = divisibility k a (b - combo2)
  | otherwise = 0
  where combo1 = mod a k
        combo2 = mod b k
        result = 1 + div (b - a) k
        l = 10^18


Mishka wants to buy some food in the nearby shop. Initially, he has $$$s$$$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $$$1 \le x \le s$$$, buy food that costs exactly $$$x$$$ burles and obtain $$$\lfloor\frac{x}{10}\rfloor$$$ burles as a cashback (in other words, Mishka spends $$$x$$$ burles and obtains $$$\lfloor\frac{x}{10}\rfloor$$$ back). The operation $$$\lfloor\frac{a}{b}\rfloor$$$ means $$$a$$$ divided by $$$b$$$ rounded down.It is guaranteed that you can always buy some food that costs $$$x$$$ for any possible value of $$$x$$$.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has $$$s=19$$$ burles then the maximum number of burles he can spend is $$$21$$$. Firstly, he can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback. Now he has $$$s=10$$$ burles, so can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback and spend it too.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a separate line and consists of one integer $$$s$$$ ($$$1 \le s \le 10^9$$$) — the number of burles Mishka initially has.

For each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.

import Control.Monad

getInt = fmap read getLine :: IO Int

main = do
    t <- getInt
    replicateM_ t $ do
        n <- getInt
        print $ n `div` 9 * 10 + n `mod` 9 - if n `mod` 9 == 0 then 1 else 0

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

process n 0 = n
process n a | a<10 = n+a
            |otherwise = process (n+ 10*(div a 10)) ((mod a 10) + (div a 10))

onecase = do
		a<-read <$> getLine ::IO Integer
		print $ process 0 a

main = do
		n<-read <$> getLine ::IO Int
		replicateM_ n onecase

import Control.Monad
import Data.Ratio
import Data.Char

solve :: Int -> Int
solve n
  | n < 10 = n
  | otherwise = a + solve ((n - a) + (floor $ a % 10))
  where
    rest = n - a
    ds = map digitToInt $ show n
    l = length ds
    a :: Int
    a = (head ds) * 10 ^ (l - 1)

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    n <- readLn :: IO Int
    print $ solve n

process :: Int -> Int
process n
    | n < 10 = n
    | otherwise = n-m + process (d+m)
    where (d,m) = n `divMod` 10

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    n <- fmap readInt getLine
    print $ process n
    run (t-1)

main :: IO ()
main = do
    t <- fmap readInt getLine
    run t

import Control.Monad

getInt = fmap read getLine :: IO Int

main = do
    t <- getInt
    replicateM_ t $ do
        n <- getInt
        if n > 9 then print $ n `div` 9 * 10 + n `mod` 9
                 else print n


A string $$$a=a_1a_2\dots a_n$$$ is called even if it consists of a concatenation (joining) of strings of length $$$2$$$ consisting of the same characters. In other words, a string $$$a$$$ is even if two conditions are satisfied at the same time:  its length $$$n$$$ is even;  for all odd $$$i$$$ ($$$1 \le i \le n - 1$$$), $$$a_i = a_{i+1}$$$ is satisfied. For example, the following strings are even: "" (empty string), "tt", "aabb", "oooo", and "ttrrrroouuuuuuuukk". The following strings are not even: "aaa", "abab" and "abba".Given a string $$$s$$$ consisting of lowercase Latin letters. Find the minimum number of characters to remove from the string $$$s$$$ to make it even. The deleted characters do not have to be consecutive.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. The descriptions of the test cases follow. Each test case consists of one string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — the length of the string $$$s$$$. The string consists of lowercase Latin letters. It is guaranteed that the sum of $$$|s|$$$ on all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single number — the minimum number of characters that must be removed to make $$$s$$$ even.

6

aabbdabdccc

zyx

aaababbb

aabbcc

oaoaaaoo

bmefbmuyw

NoteIn the first test case you can remove the characters with indices $$$6$$$, $$$7$$$, and $$$9$$$ to get an even string "aabbddcc".In the second test case, each character occurs exactly once, so in order to get an even string, you must remove all characters from the string.In the third test case, you can get an even string "aaaabb" by removing, for example, $$$4$$$-th and $$$6$$$-th characters, or a string "aabbbb" by removing the $$$5$$$-th character and any of the first three.

import Data.List (findIndex)
import Control.Monad (replicateM_)

main = read <$> getLine >>= flip replicateM_ singleCase
singleCase = getLine >>= print . minToEven 0

searchPair :: (Ord a) => Int -> [a] -> Int -> [(Int, [a])]
searchPair m [] _ = []
searchPair m (x:xs) c
  | c >= m = []
  |otherwise =
   case findWithin x xs m c of
     Just (numBw, rest) -> (numBw, rest) : searchPair numBw xs (c+1)
     Nothing -> searchPair m xs (c+1)

findWithin :: (Ord a) => a -> [a] -> Int -> Int -> Maybe (Int, [a])
findWithin _ [] _ _ = Nothing
findWithin e (x:xs) m c | c >= m = Nothing
                        | e == x = Just (c, xs)
                        | otherwise = findWithin e xs m (c+1)

minToEven :: Int -> String -> Int
minToEven a [] = a
minToEven a [x] = if x == '\r' then a else a+1
minToEven a (x:y:xs)
  | x == y = minToEven a xs
  | otherwise = case findIndex (x==) (y:xs) of
                  Nothing -> minToEven (a+1) (y:xs)
                  Just i -> case searchPair i (y:xs) 1 of
                              [] -> minToEven (a+i) (drop i xs)
                              pairs -> let (cost, rest) = minimum pairs in
                                         minToEven (a+cost) rest

import Control.Monad
import Control.Monad.State
import qualified Data.Set as Set

main :: IO ()
main = do
    n <- readLn
    replicateM_ n solvet

solvet :: IO ()
solvet = do
    str <- getLine
    let (s, r) = foldl (flip makeEven) (Set.empty, 0) str
    print (Set.size s + r)

makeEven :: Char -> (Set.Set Char, Int) -> (Set.Set Char, Int)
makeEven c (s, res) =
    if Set.member c s
        then (Set.empty, res + Set.size s - 1)
        else (Set.insert c s, res)

import           Control.Monad
import           Control.Monad.State
import Data.Set ( empty, insert, member, size, Set )

-- main = undefined

main :: IO ()
main = do
  n <- readLn
  replicateM_ n solvet

solvet :: IO ()
solvet = do
  str <- getLine
  let (MyState s r) = foldl (\s c -> execState (makeEven c) s) (MyState empty 0) str
  print (size s + r)

data MyState =
  MyState
    { msSet    :: Set Char
    , msResult :: Int
    }

makeEven :: Char -> State MyState ()
makeEven c = do
  (MyState s res) <- get
  if c `member` s
    then do
      put $ MyState empty (res + size s - 1)
    else do
      let newS = c `insert` s
      put $ MyState newS res

import qualified Data.ByteString.Char8 as B
import Data.List (findIndex)
import Control.Monad (replicateM_)

main = read <$> getLine >>= flip replicateM_ singleCase
singleCase = B.getLine >>= print . minToEven 0 . B.unpack

searchPair :: (Ord a) => Int -> [a] -> Int -> [(Int, [a])]
searchPair m [] _ = []
searchPair m (x:xs) c =
  case findWithin x xs m c of
    Just (numBw, rest) -> (numBw, rest) : searchPair m xs (c+1)
    Nothing -> searchPair m xs (c+1)

findWithin :: (Ord a) => a -> [a] -> Int -> Int -> Maybe (Int, [a])
findWithin _ [] _ _ = Nothing
findWithin e (x:xs) m c | c >= m = Nothing
                        | e == x = Just (c, xs)
                        | otherwise = findWithin e xs m (c+1)

minToEven :: Int -> String -> Int
minToEven a [] = a
minToEven a [_] = a+1
minToEven a (x:y:xs)
  | x == y = minToEven a xs
  | otherwise = case findIndex (x==) (y:xs) of
                  Nothing -> minToEven (a+1) (y:xs)
                  Just i -> case searchPair i (y:xs) 1 of
                              [] -> minToEven (a+i) (drop i xs)
                              pairs -> let (cost, rest) = minimum pairs in
                                         minToEven (a+cost) rest

import Data.List (findIndex)
import Control.Monad (replicateM_)

main = read <$> getLine >>= flip replicateM_ singleCase
singleCase = getLine >>= print . minToEven 0

searchPair :: (Ord a) => Int -> [a] -> Int -> [(Int, [a])]
searchPair m [] _ = []
searchPair m (x:xs) c =
  case findWithin x xs m c of
    Just (numBw, rest) -> (numBw, rest) : searchPair m xs (c+1)
    Nothing -> searchPair m xs (c+1)

findWithin :: (Ord a) => a -> [a] -> Int -> Int -> Maybe (Int, [a])
findWithin _ [] _ _ = Nothing
findWithin e (x:xs) m c | c >= m = Nothing
                        | e == x = Just (c, xs)
                        | otherwise = findWithin e xs m (c+1)

minToEven :: Int -> String -> Int
minToEven a [] = a
minToEven a [_] = a+1
minToEven a (x:y:xs)
  | x == y = minToEven a xs
  | otherwise = case findIndex (x==) (y:xs) of
                  Nothing -> minToEven (a+1) (y:xs)
                  Just i -> case searchPair i (y:xs) 0 of
                              [] -> minToEven (a+i) (drop i xs)
                              pairs -> let (cost, rest) = minimum pairs in
                                         minToEven (a+cost) rest


Consider the following process. You have a binary string (a string where each character is either 0 or 1) $$$w$$$ of length $$$n$$$ and an integer $$$x$$$. You build a new binary string $$$s$$$ consisting of $$$n$$$ characters. The $$$i$$$-th character of $$$s$$$ is chosen as follows:  if the character $$$w_{i-x}$$$ exists and is equal to 1, then $$$s_i$$$ is 1 (formally, if $$$i > x$$$ and $$$w_{i-x} = $$$ 1, then $$$s_i = $$$ 1);  if the character $$$w_{i+x}$$$ exists and is equal to 1, then $$$s_i$$$ is 1 (formally, if $$$i + x \le n$$$ and $$$w_{i+x} = $$$ 1, then $$$s_i = $$$ 1);  if both of the aforementioned conditions are false, then $$$s_i$$$ is 0. You are given the integer $$$x$$$ and the resulting string $$$s$$$. Reconstruct the original string $$$w$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line contains the resulting string $$$s$$$ ($$$2 \le |s| \le 10^5$$$, each character of $$$s$$$ is either 0 or 1). The second line contains one integer $$$x$$$ ($$$1 \le x \le |s| - 1$$$). The total length of all strings $$$s$$$ in the input does not exceed $$$10^5$$$.

For each test case, print the answer on a separate line as follows:   if no string $$$w$$$ can produce the string $$$s$$$ at the end of the process, print $$$-1$$$;  otherwise, print the binary string $$$w$$$ consisting of $$$|s|$$$ characters. If there are multiple answers, print any of them.

import Control.Monad

apFun :: ([t] -> t) -> [t] -> Int -> [t]
apFun f s x = let
  s1 = map pure (drop x s) ++ replicate x []
  s2 = replicate x [] ++ map pure s
  in  map f $ zipWith (++) s1 s2

solve :: String -> Int -> Maybe String
solve s x = let
  w  = apFun (minimum . ('1' :)) s x
  ns = apFun (maximum . ('0' :)) w x
  in  if  s == ns  then  Just w  else  Nothing

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    s <- getLine
    x <- read <$> getLine
    putStrLn $ case  solve s x  of
      Just w -> w
      Nothing -> "-1"


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

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

main = getLine >> getLine >>= print . solve

solve :: String -> Int
solve dominoes
    | all (== '.') dominoes = length dominoes
    | otherwise             = solve $ func dominoes

func :: String -> String
func ('R':'.':'L':xs) = '.' : func xs
func ('R':'.':xs)     = 'R' : func xs
func ('.':'L':xs)     = 'L' : func xs
func ('.':xs)         = '.' : func xs
func ( _ :xs)         = func xs
func xs               = xs

main = interact $ show . f . span (=='.') . head . tail . lines
f (a, []) = length a
f (a, b:bs)
 | b == 'L' = g bs
 | b == 'R' = length a + g (b:bs)
g [] = 0
g (x:xs)
 | x == 'R' && null (dropWhile (=='.') xs) = 0
 | x == 'R' = let (a, b) = span (=='.') xs in mod (length a) 2 + g (tail b)
 | x == '.' = let (a, b) = span (=='.') (x:xs) in length a + g b

solve :: [ (Char,Int) ] -> Int
solve []                = 0
solve (('L',b):rest)    = solve' b rest
solve xs@(('R',a):rest) = solve' 0 xs

solve' :: Int -> [ (Char,Int) ] -> Int
solve' b' (('R',a):('L',b):rest) = a-b'-1 + (if even (b-a) then 1 else 0) + solve' b rest
solve' b' (('R',a):_)            = a-b'-1
solve' b' []                     = 0 -- never happens

(-->) = flip fmap

main = do
  n <- getLine --> read :: IO Int
  doms <- getLine
  let pairs = filter (\(d,a) -> d == 'L' || d == 'R') (zip doms [1..])
  print $ solve (pairs ++ [('R',n+1)])

data LR = L | R | Vertical deriving Eq

main = do
    n <- getLine
    dominos <- getLine
    putStrLn.show $ countUp Vertical (0,0) dominos

countUp :: LR -> (Int,Int) -> String -> Int
countUp Vertical (amout,tmp) [] = amout+tmp
countUp L (amout,tmp) [] = amout+tmp
countUp R (amout,tmp) [] = amout
countUp Vertical (amout,tmp) ('.':xs) = countUp Vertical (amout,tmp+1) xs
countUp Vertical (amout,tmp) ('L':xs) = countUp L (amout,0) xs
countUp Vertical (amout,tmp) ('R':xs) = countUp R (amout+tmp,0) xs

countUp L (amout,tmp) ('.':xs) = countUp Vertical (amout+1,0) xs
countUp L (amout,tmp) ('R':xs) = countUp R (amout,0) xs

countUp R (amout,tmp) ('.':xs) = countUp R (amout,tmp+1) xs
countUp R (amout,tmp) ('L':xs) = countUp L (amout + if odd tmp then 1 else 0,0) xs

main=interact$show.solve.parse.(!!1).lines
data A = L | R | N !Int
parse :: String -> [A]
parse ('R':cs) = R : parse cs
parse ('L':cs) = L : parse cs
parse cs@(_:_) | (xs, ys) <- span ('.'==) cs = N(length xs) : parse ys
parse [] = []

solve :: [A] -> Int
solve xs = go 0 xs
   where
     go acc (R:N n:L:rest)
       | even n = go acc rest
       | otherwise = go (acc+1) rest
     go acc (R:N n:R:rest) = go acc (R:rest)
     go acc (R:L:rest) = go acc rest
     go acc (R:R:rest) = go acc (R:rest)
     go acc (L:rest) = go acc rest
     go acc (N n:R:rest) = go (acc+n) (R:rest)
     go acc (N n:L:rest) = go acc rest
     go acc [N n] = acc + n
     go acc [R, N n] = acc
     go acc [R] = acc
     go acc [] = acc

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

import Data.Bits
import Data.Char
import Data.Either
import Data.Function
import Data.IORef
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Tuple

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

import Debug.Trace
import Text.Printf
-- }}}
-- silly utilities {{{
(#) = flip ($)
infixl 0 #

glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)

(!>) :: Seq a -> Int -> a
(!>) = Seq.index
-- }}}
-- input and output {{{
inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

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

pushStart s = let (ls, rs) = span (== '.') s in case rs of
	"" -> length ls
	('L':xs) -> push xs
	('R':xs) -> length ls + pushR xs
	_ -> error "what?"

pushR s = let (ls, rs) = span (== '.') s in case rs of
	"" -> 0
	('L':xs) -> (length ls `rem` 2) + push xs
	_ -> error "what?"

push s = let (ls, rs) = span (== '.') s in case rs of
	"" -> length ls
	('R':xs) -> length ls + pushR xs
	_ -> error "what?"

main :: IO ()
main = do
	void getLine
	print . pushStart =<< getLine

data LR = L | R | Vertical deriving Eq

main = do
    n <- getLine
    dominos <- getLine
    putStrLn.show $ countUp Vertical (0,0) dominos

countUp :: LR -> (Int,Int) -> String -> Int
countUp _ (amout,tmp) [] = amout+tmp
countUp Vertical (amout,tmp) ('.':xs) = countUp Vertical (amout,tmp+1) xs
countUp Vertical (amout,tmp) ('L':xs) = countUp L (amout,0) xs
countUp Vertical (amout,tmp) ('R':xs) = countUp R (amout+tmp,0) xs

countUp L (amout,tmp) ('.':xs) = countUp Vertical (amout+1,0) xs
countUp L (amout,tmp) ('R':xs) = countUp R (amout,0) xs

countUp R (amout,tmp) ('.':xs) = countUp R (amout,tmp+1) xs
countUp R (amout,tmp) ('L':xs) = countUp L (amout + if odd tmp then 1 else 0,0) xs


You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \le n \le 100$$$, $$$0 \le x \le 100$$$, $$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

For each test case print one integer — the maximum distance between two rivaling students which you can obtain.

NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students.

import Control.Monad

solve :: Int -> Int -> Int -> Int -> Int
solve n x a b = min (n-1) (abs (a-b)+x)

main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

routine :: IO ()
routine = do
  [n,x,a,b] <- fmap (map read.words) getLine
  print $ solve n x a b

-- 2019-11-20 20:26:12.553249308 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 20:16:55.732621122 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 20:19:05.325954742 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 14:25:18.674293017 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-19 11:27:55.861773021 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourIntsToInt
parseFourIntsToInt :: String -> Maybe (Int, Int, Int, Int)
parseFourIntsToInt i = do {when (length (lines i) /= 1) Nothing;
                           ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                           when (length ns /= 4) Nothing;
                           let {[a, b, c, d] = ns};
                           return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 20:20:24.758961377 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 23:20:33.466947138 UTC
import Data.Maybe
import Data.Char
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 23:28:27.599374755 UTC
import Data.Maybe
import Data.Char
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 14:32:18.789734853 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> min (flip (-) 1 a) (b + abs (d - c))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- http://codeforces.com/problemset/problem/1257/A

data Case = Case Int Int Int Int

toCase :: String -> Case
toCase inputLine = do
  let ints = map read $ words inputLine :: [Int]
  Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)

solve :: Case -> Int
solve (Case n x a b)
  | x == 0 = abs (a - b)
  | first == 1 && last == n = abs (a - b)
  | x >= 2 && first > 1 && last < n = solve $ Case n (x - 2) (first - 1) (last + 1)
  | first > 1 = solve $ Case n (x - 1) (first - 1) last
  | last < n = solve $ Case n (x - 1) first (last + 1)
  | otherwise = abs (a - b)
  where first = min a b
        last  = max a b

-- solve :: Case -> Int
-- solve (Case n x a b)
--   | (a == 1) && (b == n) = abs(a - b)
--   | (a == n) && (b == 1) = abs(a - b)
--   | otherwise = moveStudents $ Case n x a b

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines

-- http://codeforces.com/problemset/problem/1257/A

data Case = Case Int Int Int Int

toCase :: String -> Case
toCase inputLine = do
  let ints = map read $ words inputLine :: [Int]
  Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)

moveStudents :: Case -> Int
moveStudents (Case n x a b)
  | x == 0 = abs(a - b)
  | (min a b) > 1 = moveStudents $ Case n (x - 1) ((min a b) - 1) (max a b)
  | (max a b) < n = moveStudents $ Case n (x - 1) (min a b) ((max a b) + 1)
  | otherwise = abs(a - b)

solve :: Case -> Int
solve (Case n x a b)
  | (a == 1) && (b == n) = abs(a - b)
  | (a == n) && (b == 1) = abs(a - b)
  | otherwise = moveStudents $ Case n x a b

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines

-- http://codeforces.com/problemset/problem/1257/A

data Case = Case Int Int Int Int

toCase :: String -> Case
toCase inputLine = do
  let ints = map read $ words inputLine :: [Int]
  Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)

solve :: Case -> Int
solve (Case n x a b)
  | x == 0 = abs (a - b)
  | first == 1 && last == n = abs (a - b)
  | x >= 2 && first > 1 && last < n = solve $ Case n (x - 2) (first - 1) (last + 1)
  | first > 1 = solve $ Case n (x - 1) (first - 1) last
  | last < n = solve $ Case n (x - 1) first (last + 1)
  | otherwise = abs (a - b)
  where first = min a b
        last  = max a b

main :: IO ()
main = interact $ unlines .                     -- Join elements with \n. Ex: unlines ["1", "2", "3"] -> "1\n2\n3\n"
                  map (show . solve . toCase) . -- For each element do: 1) toCase, 2) solve, 3) show
                  tail .                        -- Drop the first element (we dont need it)
                  lines                         -- Read lines from stdin

-- http://codeforces.com/problemset/problem/1257/A

data Case = Case Int Int Int Int

toCase :: String -> Case
toCase inputLine = do
  let ints = map read $ words inputLine :: [Int]
  Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)

solve :: Case -> Int
solve (Case n x a b)
  | x == 0 = abs(a - b)
  | (min a b) > 1 = solve $ Case n (x - 1) ((min a b) - 1) (max a b)
  | (max a b) < n = solve $ Case n (x - 1) (min a b) ((max a b) + 1)
  | otherwise = abs(a - b)

-- solve :: Case -> Int
-- solve (Case n x a b)
--   | (a == 1) && (b == n) = abs(a - b)
--   | (a == n) && (b == 1) = abs(a - b)
--   | otherwise = moveStudents $ Case n x a b

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines

-- http://codeforces.com/problemset/problem/1257/A

data Case = Case Int Int Int Int

toCase :: String -> Case
toCase inputLine = do
  let ints = map read $ words inputLine :: [Int]
  Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)

solve :: Case -> Int
solve (Case n x a b)
  | x == 0 = abs(a - b)
  | x >= 2 && first > 1 && last < n = solve $ Case n (x - 2) (first - 1) (last + 1)
  | first > 1 = solve $ Case n (x - 1) (first - 1) last
  | last < n = solve $ Case n (x - 1) first (last + 1)
  | otherwise = abs(a - b)
  where first = min a b
        last  = max a b

-- solve :: Case -> Int
-- solve (Case n x a b)
--   | (a == 1) && (b == n) = abs(a - b)
--   | (a == n) && (b == 1) = abs(a - b)
--   | otherwise = moveStudents $ Case n x a b

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines

module Main where

import Control.Monad

main :: IO ()
main = do
    t <- (read::String->Int) <$> getLine

    replicateM_ t $ do
        [n, x, a, b] <- fmap (read::String->Int) . words <$> getLine
        let mi = min a b
        let ma = max a b
        let dma = n - ma
        let dmi = mi - 1
        let d = dma + dmi
        let s = min d x
        print $ abs (a-b) + s
        return ()
    return ()

main = interact $ unlines . map show . solveTests . map read . words

solveTests (t:ls) = solveTests' t ls

solveTests' 0 _ = []
solveTests' t (n:x:a:b:ls) = (min (n-1) (abs (a-b) + x)) : solveTests' (t-1) ls
solveTests' _ _ = []

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

onecase= do
		[n,x,a,b]<-map read <$> words <$> getLine :: IO [Int]
		print $ min (n-1) (x + (abs (a-b)))

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

--ghc 7.10

maxDistance :: (Integral a) => (a,a,a,a) -> a
maxDistance (n,x,a,b) = min (n-1) (x + abs (a-b))

readLine :: String -> (Int,Int,Int,Int)
readLine str = (n,x,a,b)
    where [n,x,a,b] = map read . words $ str

main = do
    tStr <- getLine
    contents <- getContents
    let xs = map readLine . lines $ contents
    sequence . map print . map maxDistance $ xs

-- 2019-11-20 20:16:06.271115345 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> flip (-) 1 (min c (d + (b + a)))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 14:22:25.070625994 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> flip (-) 1 (min c (d + (b + a)))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 20:13:03.499329669 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> flip (-) 1 (min c (d + (b + a)))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 23:28:44.008450939 UTC
import Data.Maybe
import Data.Char
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \_ _ c _ -> flip (-) 1 c
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 23:25:00.269823993 UTC
import Data.Maybe
import Data.Char
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> flip (-) 1 (min c (d + (b + a)))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 20:17:13.069561071 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \_ _ c _ -> flip (-) 1 c
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-25 10:38:41.233162656 UTC
import Data.Maybe
import Data.Char
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> flip (-) 1 (min c (b - (d - a)))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-19 11:24:32.055120469 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourIntsToInt
parseFourIntsToInt :: String -> Maybe (Int, Int, Int, Int)
parseFourIntsToInt i = do {when (length (lines i) /= 1) Nothing;
                           ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                           when (length ns /= 4) Nothing;
                           let {[a, b, c, d] = ns};
                           return (a, b, c, d)}
solve = \a b c d -> iF (d >= a) b (flip (-) 1 c)
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 14:25:37.164105911 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \_ _ c _ -> flip (-) 1 c
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 23:18:51.596198974 UTC
import Data.Maybe
import Data.Char
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> flip (-) 1 (min c (d + (b + a)))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 23:21:30.976993029 UTC
import Data.Maybe
import Data.Char
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \_ _ c _ -> flip (-) 1 c
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 14:33:40.310577348 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> nat_para d b (\_ _ -> nat_para c a (\g _ -> g))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 20:19:22.548650727 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \a b c d -> flip (-) 1 (min c (d + (b + a)))
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 20:22:30.7083905 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b, c, d) = show $ f a b c d
parser :: String -> (Int, Int, Int, Int)
parser = fromJust . parseFourInts
parseFourInts :: String -> Maybe (Int, Int, Int, Int)
parseFourInts i = do {when (length (lines i) /= 1) Nothing;
                      ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                      when (length ns /= 4) Nothing;
                      let {[a, b, c, d] = ns};
                      return (a, b, c, d)}
solve = \_ _ c _ -> flip (-) 1 c
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- http://codeforces.com/problemset/problem/1257/A

data Case = Case Int Int Int Int

toCase :: String -> Case
toCase inputLine = do
  let ints = map read $ words inputLine :: [Int]
  Case (ints !! 0) (ints !! 1) (ints !! 2) (ints !! 3)

solve :: Case -> Int
solve (Case n x a b)
  | x == 0 = abs(a - b)
  | first > 1 && last < n = solve $ Case n (x - 2) (first - 1) (last + 1)
  | first > 1 = solve $ Case n (x - 1) (first - 1) last
  | last < n = solve $ Case n (x - 1) first (last + 1)
  | otherwise = abs(a - b)
  where first = min a b
        last  = max a b

-- solve :: Case -> Int
-- solve (Case n x a b)
--   | (a == 1) && (b == n) = abs(a - b)
--   | (a == n) && (b == 1) = abs(a - b)
--   | otherwise = moveStudents $ Case n x a b

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines


Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $$$n$$$ sessions follow the identity permutation (ie. in the first game he scores $$$1$$$ point, in the second game he scores $$$2$$$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $$$[1,2,3]$$$ can yield $$$[3,1,2]$$$ but it cannot yield $$$[3,2,1]$$$ since the $$$2$$$ is in the same position. Given a permutation of $$$n$$$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $$$10^{18}$$$.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the given permutation. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ ($$$1 \leq a_{i} \leq n$$$)  — the initial permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.

NoteIn the first permutation, it is already sorted so no exchanges are needed.It can be shown that you need at least $$$2$$$ exchanges to sort the second permutation.$$$[3, 2, 4, 5, 1, 6, 7]$$$Perform special exchange on range ($$$1, 5$$$)$$$[4, 1, 2, 3, 5, 6, 7]$$$Perform special exchange on range ($$$1, 4$$$)$$$[1, 2, 3, 4, 5, 6, 7]$$$

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : perm : rest) = (itoline . solve . linetois) perm : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words
    istoline = unwords . (map itoline)
    linestoiss = (map linetois) . lines
    isstolines = unlines . (map istoline)

solve :: [Int] -> Int
solve xs | null $ mispos xs = 0
         | contiguous $ mispos xs = 1
         | otherwise = 2 where
      mispos xs =  [a | (a,x) <- zip [1..] xs, a /= x ]
      contiguous as = all (==1) $ zipWith (-) ((drop 1) as) as

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Control.Monad
import Data.List

main = getLine >>= flip replicateM_ test . read

test = do
  getLine
  as <- map read . words <$> getLine
  print $
    if as == sort as
      then 0
      else
        if or $ dropWhile (== True) $ dropWhileEnd (== True) $ zipWith (==) [1 ..] as
          then 2
          else 1

import Control.Monad
import Data.List

solve :: [Int] -> Int
solve xs
  | null pruned = 0
  | null aligns = 1
  | otherwise = 2
  where
    pruned = dropWhileEnd id $ dropWhile id $ zipWith (==) [1..] xs
    aligns = filter id $ pruned

main :: IO ()
main = do
  t <- read <$> getLine
  tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)
  mapM_ (print . solve) tests

import Control.Monad
import Data.List

solve :: [Int] -> Int
solve xs
  | null pruned = 0
  | aligns == 0 = 1
  | otherwise = 2
  where
    pruned = dropWhileEnd id $ dropWhile id $ zipWith (==) [1..] xs
    aligns = length $ filter id $ pruned

main :: IO ()
main = do
  t <- read <$> getLine
  tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)
  mapM_ (print . solve) tests

import Control.Monad

solve :: [Int] -> Int
solve xs
  | null pruned = 0
  | aligns == 0 = 1
  | otherwise = 2
  where
    pruned = dropWhile same $ reverse $ dropWhile same $ zip [1..] xs
    aligns = length $ filter same $ pruned
    same (a, b) = a == b

main :: IO ()
main = do
  t <- read <$> getLine
  tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)
  mapM_ (print . solve) tests

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : p : rest) = (itoline . solve . linetois) p : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words
    istoline = unwords . (map itoline)
    linestoiss = (map linetois) . lines
    isstolines = unlines . (map istoline)

solve :: [Int] -> Int
solve xs | null $ mispos xs = 0
         | contiguous $ mispos xs = 1
         | otherwise = 2 where
      mispos as =  [b | (a,b) <- zip [1..] as, a /= b ]
      contiguous as = all (==1) $ zipWith (-) as ((drop 1) as)

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : p : rest) = (itoline . solve . linetois) p : tcio rest where
    linetoi = read
    itoline = show
    linetois = (map linetoi) . words
    istoline = unwords . (map itoline)
    linestoiss = (map linetois) . lines
    isstolines = unlines . (map istoline)

solve :: [Int] -> Int
solve xs | null $ mispos xs = 0
         | contiguous $ mispos xs = 1
         | otherwise = 2 where
      mispos xs =  [a | (a,x) <- zip [1..] xs, a /= x ]
      contiguous as = all (==1) $ zipWith (-) as ((drop 1) as)

import Control.Monad

solve :: [Int] -> Int
solve xs
  | aligns == length xs = 0
  | aligns == 0 = 1
  | otherwise = 2
  where
    aligns = length $ filter same $ dropWhile same $ reverse $ dropWhile same $ zip [1..] xs
    same (a, b) = a == b

main :: IO ()
main = do
  t <- read <$> getLine
  tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)
  mapM_ (print . solve) tests

import Control.Monad

solve :: [Int] -> Int
solve xs
  | aligns == length xs = 0
  | aligns == 0 = 1
  | otherwise = 2
  where
    aligns = length $ filter (\(a, b) -> a == b) $ zip [1..] xs

main :: IO ()
main = do
  t <- read <$> getLine
  tests <- replicateM t (fmap (map read . words) $ getLine >> getLine)
  mapM_ (print . solve) tests


You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) — the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.

NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.

readInt :: IO Int
readInt = do
        t <- getLine
        return $ read t

readInts :: IO [Int]
readInts = fmap (map read . words) getLine

numWith :: (z -> Bool) -> [z] -> Int
numWith t s = foldr (\a -> \b -> if t a then b+1 else b) 0 s

balanceList :: String -> [Int]
balanceList s = foldl (\a -> \b -> (if b == '1' then (head a) - 1 else (head a) + 1) : a) [0] s

valid :: Int -> Int -> Bool
valid d b = not (d < 0 && b > 0 || d > 0 && b < 0)

compute :: String -> Int -> String
compute s x
        | (head balance == 0) = if x == 0 || any (==x) balance then "-1" else "0"
        | otherwise = show $ numWith (\c -> valid (x - c) (head balance) && (x - c) `mod` (head balance) == 0) $ tail balance
        where balance = balanceList s

solve :: Int -> IO ()
solve 0 = return ()
solve t = do
        [_,x] <- readInts
        s <- getLine
        putStrLn $ compute s x
        solve (t-1)

main :: IO ()
main = do
        t <- readInt
        solve t

import Data.Ord
import Data.Int
import qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s DSeq.|> x
    in aux DSeq.Empty

type EIO a = ExceptT String IO a

get :: Read a => EIO a
get = ExceptT $ liftM readEither getToken
gets :: EIO String
gets = ExceptT $ liftM Right getToken
puts :: String -> EIO ()
puts = lift . putStr
putsln :: String -> EIO ()
putsln = lift . putStrLn
put :: Show a => a -> EIO ()
put = putsln . show
putln :: Show a => a -> EIO ()
putln = putsln . show
showList :: Show a => [a] -> String
showList [] = []
showList (x : l) = shows x $ showChar ' ' $ showList l

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
main_ = do
    t <- get
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    (n, x) <- liftM2 (,) get get
    cs <- gets
    putln $ f2 cs n x

f2 :: String -> Int -> Int64 -> Int64
f2 cs n x = let (s, ks) = foldl (\(sum, seq) i -> if i == '0' then (sum + 1, seq DSeq.|> (sum + 1)) else (sum - 1, seq DSeq.|> (sum - 1))) (0, DSeq.Empty DSeq.|> 0) cs in
            let kl = toList $ DSeq.take n ks
            in
            if s == 0 then
                let count = foldl (\sum i -> if i == x then sum + 1 else sum) 0 kl in
                if count /= 0 then -1
                else 0
            else
                let count = foldl (\sum i -> if (mod (i - x) s) == 0 && ((x - i == 0) || ((x - i) > 0 && s > 0) || ((x - i) < 0 && s < 0)) then sum + 1 else sum) 0 kl in
                count

readInt :: IO Int
readInt = do
        t <- getLine
        return $ read t

readInts :: IO [Int]
readInts = fmap (map read . words) getLine

numWith :: (z -> Bool) -> [z] -> Int
numWith t s = foldr (\a -> \b -> if t a then b+1 else b) 0 s

balanceList :: String -> [Int]
balanceList s = foldl (\a -> \b -> (if b == '1' then (head a) - 1 else (head a) + 1) : a) [0] s

compute :: String -> Int -> String
compute s x
        | (head balance == 0) = if x == 0 || any (==x) balance then "-1" else "0"
        | otherwise = show $ numWith (\c -> (x - c) * (head balance) >= 0 && (x - c) `mod` (head balance) == 0) $ tail balance
        where balance = balanceList s

solve :: Int -> IO ()
solve 0 = return ()
solve t = do
        [_,x] <- readInts
        s <- getLine
        putStrLn $ compute s x
        solve (t-1)

main :: IO ()
main = do
        t <- readInt
        solve t

readInt :: IO Int
readInt = do
        t <- getLine
        return $ read t

readInts :: IO [Int]
readInts = fmap (map read . words) getLine

numWith :: (z -> Bool) -> [z] -> Int
numWith t s = foldr (\a -> \b -> if t a then b+1 else b) 0 s

balanceList :: String -> [Int]
balanceList s = foldl (\a -> \b -> (if b == '1' then (head a) - 1 else (head a) + 1) : a) [0] s

compute :: String -> Int -> String
compute s x
        | (head balance == 0) = if x == 0 || any (==x) balance then "-1" else "0"
        | otherwise = show $ numWith (\c -> (x - c) * (head balance) >= 0 && abs (x - c) `mod` (abs (head balance)) == 0) $ tail balance
        where balance = balanceList s

solve :: Int -> IO ()
solve 0 = return ()
solve t = do
        [_,x] <- readInts
        s <- getLine
        putStrLn $ compute s x
        solve (t-1)

main :: IO ()
main = do
        t <- readInt
        solve t


The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k × d bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers.

The first output line contains two space-separated integers n and l (1 ≤ n, l ≤ 100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated n integers ai. They are the lengths of initial stripes in bourlemeters (1 ≤ ai ≤ 100).

Print the single number — the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0.

NoteIn the first sample test the required window is 2 × 4 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves.

getA = fmap (map read . words) getLine
main = do
	[n, l] <- getA
	a <- getA
	putStrLn $ show $ maximum $ 0:[i * sum (map (`div` i) a) | i <- [l .. maximum a]]

solve :: Int -> [Int] -> Int
solve l xs  =  maximum $ 0 : [k * d k | k <- [l..maximum xs]]
  where
    d k  =  sum $ map (flip div k) xs

main :: IO ()
main  =  do
    [n, l]  <-  fmap (map read . words) getLine
    xs  <-  fmap (map read . words) getLine
    print $ solve l xs

solve (l:xs) = maximum $ map getSquare [l..100]
    where getSquare l = l * foldl (\ans x -> ans + x `div` l) 0 xs
main = interact $ show.solve.map read.tail.words

f (l:p) = maximum $ map s [l..100]
    where s l = l * foldl (\a x -> a + x `div` l) 0 p
main = interact $ show.f.map read.tail.words

import Prelude
import List
import Char

main = interact q

q = func.map toInt.tail.words

func::[Int]->String
func (a:xs) = toString$solve a (sort xs)

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

maximum' [] = 0
maximum' a  = maximum a

solve::Int->[Int]->Int
solve a b= maximum'$map (solve' b) [a..b']
      where
        b' = last b

solve' b a = sum$map (f' a) b

f'::Int->Int->Int
f' a b = c*a
    where
      c = b `div` a

main = interact f
f input = output where
  [[n,l],a] = map (map (read::String->Int)) $ map words $ lines input
  output = show ans
  k d = sum [div x d|x<-a]
  ans = foldl max 0 [k d * d|d<-[l..(foldl1 max a)]]

import Data.Char (ord)

solveFor v n x = (*) x $ sum $ map (`div` x) v

solve n l v maxv = maximum $ (:) 0 $ map (solveFor v n) $ [l..maxv]

main = do
  [n, l] <- fmap ((map (\x -> read x::Int)) . words) getLine
  v <- fmap ((map (\x -> read x::Int)) . words) getLine
  print $ solve n l v $ maximum v

solve (l:xs) = let q = max l $ minimum $ 101:filter (>=l) xs
               in q * foldl (\ans x -> ans + x `div` q) 0 xs
main = interact $ show.solve.map read.tail.words

solve (l:xs) = let q = max l $ minimum xs
               in q * foldl (\ans x -> ans + x `div` q) 0 xs
main = interact $ show.solve.map read.tail.words

solve (l:xs) = l * foldl (\ans x -> ans + x `div` l) 0 xs
main = interact $ show.solve.map read.tail.words

import Prelude
import List
import Char

main = interact q

q = func.map toInt.tail.words

func::[Int]->String
func (a:xs) = toString$solve a xs

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve::Int->[Int]->Int
solve a = sum.map (f' a)

f'::Int->Int->Int
f' a b = c*a
    where
      c = b `div` a


There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.

The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j.

Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added.

NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.

import Debug.Trace (trace)
import Data.Vector ((!), Vector, fromList, imap, length, minimum)
import Data.List (sort)
import Control.Monad (liftM, replicateM)
import Prelude hiding (minimum, length)

data Beacon = Beacon { position :: Int, power :: Int }
  deriving (Eq, Ord, Show)

solve :: Vector Beacon -> Int
solve a = minimum dp'
 where
  n = length a
  dp = fromList [solve' i | i <- [0..n]]
  dp' = imap (\ i x -> n - i + x) dp

  solve' :: Int -> Int
  solve' 0 = 0
  solve' n = (dp ! idxFirstDestroyed) + n - idxFirstDestroyed - 1
   where
    posFirstDestroyed = position (a ! (n - 1)) - power (a ! (n - 1))
    idxFirstDestroyed = lowerBound 0 (length a - 1) posFirstDestroyed

  lowerBound :: Int -> Int -> Int -> Int
  lowerBound lo hi _ | lo == hi = lo
  lowerBound lo hi x =
    let mid = lo + (hi - lo) `div` 2 in
    if position (a ! mid) < x
      then lowerBound (mid + 1) hi x
      else lowerBound lo mid x

readBeacon :: IO Beacon
readBeacon = do
  (pos:pow:_) <- getLine >>= (return . map read . words)
  return $ Beacon pos pow

main = do
  nBeacons <- readLn :: IO Int
  beacons <- replicateM nBeacons readBeacon >>= (return . fromList . sort)
  putStrLn $ show $ solve beacons