Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $$$a$$$ of $$$n$$$ non-negative integers.Dark created that array $$$1000$$$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) and replaces all missing elements in the array $$$a$$$ with $$$k$$$.Let $$$m$$$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $$$|a_i - a_{i+1}|$$$ for all $$$1 \leq i \leq n - 1$$$) in the array $$$a$$$ after Dark replaces all missing elements with $$$k$$$.Dark should choose an integer $$$k$$$ so that $$$m$$$ is minimized. Can you help him?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-1 \leq a_i \leq 10 ^ {9}$$$). If $$$a_i = -1$$$, then the $$$i$$$-th integer is missing. It is guaranteed that at least one integer is missing in every test case. It is guaranteed, that the sum of $$$n$$$ for all test cases does not exceed $$$4 \cdot 10 ^ {5}$$$.

Print the answers for each test case in the following format: You should print two integers, the minimum possible value of $$$m$$$ and an integer $$$k$$$ ($$$0 \leq k \leq 10^{9}$$$) that makes the maximum absolute difference between adjacent elements in the array $$$a$$$ equal to $$$m$$$. Make sure that after replacing all the missing elements with $$$k$$$, the maximum absolute difference between adjacent elements becomes $$$m$$$. If there is more than one possible $$$k$$$, you can print any of them.

NoteIn the first test case after replacing all missing elements with $$$11$$$ the array becomes $$$[11, 10, 11, 12, 11]$$$. The absolute difference between any adjacent elements is $$$1$$$. It is impossible to choose a value of $$$k$$$, such that the absolute difference between any adjacent element will be $$$\leq 0$$$. So, the answer is $$$1$$$.In the third test case after replacing all missing elements with $$$6$$$ the array becomes $$$[6, 6, 9, 6, 3, 6]$$$.  $$$|a_1 - a_2| = |6 - 6| = 0$$$;  $$$|a_2 - a_3| = |6 - 9| = 3$$$;  $$$|a_3 - a_4| = |9 - 6| = 3$$$;  $$$|a_4 - a_5| = |6 - 3| = 3$$$;  $$$|a_5 - a_6| = |3 - 6| = 3$$$. So, the maximum difference between any adjacent elements is $$$3$$$.

solve :: [Integer] -> (Integer, Integer)
solve xs = (m, k)
  where allPairs = zip xs (tail xs)
        numbersThatMatter = [if a == (-1) then b else a | (a, b) <- allPairs, (a == (-1) || b == (-1)) && b /= a]
        k = if null numbersThatMatter then 0 else div (minimum numbersThatMatter + maximum numbersThatMatter) 2
        m = maxDiff xs k

maxDiff :: [Integer] -> Integer -> Integer
maxDiff [] _ = 0
maxDiff [_] _ = 0
maxDiff (a:b:rest) k = max (abs (a'-b')) (maxDiff (b:rest) k)
  where a' = if a == (-1) then k else a
        b' = if b == (-1) then k else b

parse :: (String, String) -> String
parse (_, b) = (show m) ++ " " ++ (show k)
  where numbers = map (\x -> read x :: Integer) $ words b
        (m, k) = solve numbers

takeLines :: [String] -> [(String, String)]
takeLines [] = []
takeLines (a:b:rest) = (a, b):takeLines rest

main :: IO ()
main = interact (unlines . map parse . takeLines . tail . lines)


Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.

The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message. The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper. Here |a| means the length of the string a.

Print two integers separated by a space:   the first number is the number of times Tanya shouts "YAY!" while making the message,  the second number is the number of times Tanya says "WHOOPS" while making the message.

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  s <- getLine
  t <- getLine

  let
    s' = accumArray (+) (0 :: Int) (chr 0, chr 255) $ zip s (repeat 1) :: Array Char Int
    t' = accumArray (+) (0 :: Int) (chr 0, chr 255) $ zip t (repeat 1) :: Array Char Int

    f c = (c1, c2)
      where
        m1 = min (s'!c) (t'!c)
        m2 = min (s'!c') (t'!c')
        c1 = m1 + m2
        c2 = min (t'!c + t'!c' - c1) (s'!c - m1 + s'!c' - m2)
        c'= toUpper c

    cs = map f ['a'..'z']

  putStrLn $ show (sum $ map fst cs) ++ " " ++ show (sum $ map snd cs)

module Main where
import Control.Applicative
import Control.Monad
import Data.Char
import Data.Ord
import Data.List
import qualified Data.Map.Lazy as M
import Data.Maybe

main :: IO ()
main = do
  s <- getLine
  t <- getLine
  mapM_ (putStr . (" "++) . show) $ sol s t

sol s t = map (sum . M.elems) [mi, li]
  where
  ms = M.fromListWith (+) $ zip s (repeat 1)
  mt = M.fromListWith (+) $ zip t (repeat 1)
  mi = M.intersectionWith min ms mt
  ds = M.differenceWith (\a b -> if a>b then Just (a-b) else Nothing) ms mi
  dt = M.differenceWith (\a b -> if a>b then Just (a-b) else Nothing) mt mi
  ls = M.mapKeysWith (+) toLower ds
  lt = M.mapKeysWith (+) toLower dt
  li = M.intersectionWith min ls lt

import System.IO
import Control.Applicative
import Debug.Trace
import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST
import Data.List
import Data.Char
import qualified Data.Set as Set

-- traceDebug = trace
traceDebug _ x = x

succRevStr [] = "a"
succRevStr ('z':tl) = 'a' : succRevStr tl
succRevStr ( c :tl) = succ c : tl

succStr s =
    reverse . succRevStr . reverse $ s

groupCount s =
    let s' = group . sort $ s
    in  map (\l -> (head l, length l)) s'

main = do
    s <- getLine
    t <- getLine
    let sg = groupCount s
        tg = groupCount t

        searchLetter bag (c,n) =
          case lookup c bag of
                    Nothing -> 0
                    Just x' -> min n x'

        yay = sum . map (searchLetter tg) $ sg

        sg' = groupCount $ map toLower s
        tg' = groupCount $ map toLower t

        yay_whoops = sum . map (searchLetter tg') $ sg'

    -- traceShow sg $ do
    -- traceShow tg $ do
    -- when (yay == 198087) $
      -- putStrLn ("Sum is " ++ show (yay_whoops) ++ " and length is " ++ show (length s))
    putStrLn $ show yay ++ " " ++ show (yay_whoops - yay)

import Data.List
import qualified Data.Map as DM
import Data.Maybe

getMap :: String -> DM.Map Char Int
getMap = foldl' (\ acc x -> DM.insertWith (+) x 1 acc) DM.empty

solve :: String -> String -> (Int, Int)
solve s t =
    let m1 = getMap s
        m2 = getMap t
    in foldl' (\ (a, b) (c1, c2) ->
                let (a1, b1) = getBest m1 m2 c1 c2 in (a + a1, b + b1))
              (0, 0)
              (zip ['a'..'z'] ['A'..'Z'])
    where
        getBest :: DM.Map Char Int -> DM.Map Char Int -> Char -> Char -> (Int, Int)
        getBest m1 m2 lower upper =
            let cntLower1 = fromMaybe 0 (DM.lookup lower m1)
                cntLower2 = fromMaybe 0 (DM.lookup lower m2)
                cntUpper1 = fromMaybe 0 (DM.lookup upper m1)
                cntUpper2 = fromMaybe 0 (DM.lookup upper m2)
                goodLower = min cntLower1 cntLower2
                goodUpper = min cntUpper1 cntUpper2
                rest1 = cntLower1 + cntUpper1 - goodLower - goodUpper
                rest2 = cntLower2 + cntUpper2 - goodLower - goodUpper
                rest = min rest1 rest2
            in (goodLower + goodUpper, rest)

main = do
    s <- getLine
    t <- getLine
    let (a, b) = solve s t
    putStrLn $ show a ++ " " ++ show b

import qualified Data.Map.Strict as M
import Data.Char (toUpper, toLower)

type TanyaMap = M.Map Char Integer

occurrences :: String -> TanyaMap
occurrences = foldl (\acc ch -> M.insertWith (+) ch 1 acc) M.empty

find def ch map = (M.findWithDefault def ch map, ch)
findCaseI def ch map =
    let lower = find 0 (toLower ch) map in
        if fst lower > 0
            then lower
            else find 0 (toUpper ch) map

count :: (Integer -> Char -> TanyaMap -> (Integer, Char)) -> TanyaMap -> TanyaMap -> (Integer, TanyaMap, TanyaMap)
count findFu strOcc lettersOcc = foldl processChar (0, strOcc, lettersOcc) (M.toList strOcc)
    where
    processChar (yayps, strOcc, lettersOcc) (ch, n) =
        let (available, ach) = findFu 0 ch lettersOcc in
            if available > n
            then
                (yayps + n, M.delete ch strOcc, M.insertWith (flip (-)) ach n lettersOcc)
            else
                if available == n
                then
                    (yayps + n, M.delete ch strOcc, M.delete ach lettersOcc)
                else
                    (yayps + available, M.insertWith (flip (-)) ch available strOcc, M.delete ach lettersOcc)

countYay = count find
countWhoops = count findCaseI

main :: IO ()
main = do
    str <- getLine
    letters <- getLine
    let (strOcc, lettersOcc) = (occurrences str, occurrences letters)
        (yay, newStrOcc, newLettersOcc) = countYay strOcc lettersOcc
        (whoops, newStrOcc1, newLettersOcc1) = countWhoops newStrOcc newLettersOcc

    putStrLn $ unwords [show yay, show whoops]

import System.IO
import Control.Applicative
import Debug.Trace
import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST
import Data.List
import qualified Data.Set as Set

-- traceDebug = trace
traceDebug _ x = x

succRevStr [] = "a"
succRevStr ('z':tl) = 'a' : succRevStr tl
succRevStr ( c :tl) = succ c : tl

succStr s =
    reverse . succRevStr . reverse $ s

groupCount s =
    let s' = group . sort $ s
    in  map (\l -> (head l, length l)) s'

main = do
    s <- getLine
    t <- getLine
    let sg = groupCount s
        tg = groupCount t

        searchLetter (c,n) =
          traceShow (c,n) $
          let x = case lookup c tg of
                    Nothing -> 0
                    Just x' -> x'
          in traceShow (x, n-x) $ (min n x, max 0 $ n-x)

        counts = map searchLetter sg

        (yay,whoops) = foldl sumPair (0,0) counts
        sumPair (a,b) (a',b') = (a+a', b+b')

    traceShow sg $ do
    traceShow tg $ do
    putStrLn $ show yay ++ " " ++ show whoops

import System.IO
import Control.Applicative
import Debug.Trace
import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST
import Data.List
import qualified Data.Set as Set

-- traceDebug = trace
traceDebug _ x = x

succRevStr [] = "a"
succRevStr ('z':tl) = 'a' : succRevStr tl
succRevStr ( c :tl) = succ c : tl

succStr s =
    reverse . succRevStr . reverse $ s

groupCount s =
    let s' = group . sort $ s
    in  map (\l -> (head l, length l)) s'

main = do
    s <- getLine
    t <- getLine
    let sg = groupCount s
        tg = groupCount t

        searchLetter (c,n) =
          traceShow (c,n) $
          let x = case lookup c tg of
                    Nothing -> 0
                    Just x' -> x'
          in traceShow (x, n-x) $ (min n x, max 0 $ n-x)

        counts = map searchLetter sg

        (yay,whoops) = foldl sumPair (0,0) counts
        sumPair (a,b) (a',b') = (a+a', b+b')

    traceShow sg $ do
    traceShow tg $ do
    when (yay == 198087) $
      putStrLn ("Sum is " ++ show (yay + whoops) ++ " and length is " ++ show (length s))
    putStrLn $ show yay ++ " " ++ show whoops

import System.IO
import Control.Applicative
import Debug.Trace
import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST
import Data.List
import qualified Data.Set as Set

-- traceDebug = trace
traceDebug _ x = x

succRevStr [] = "a"
succRevStr ('z':tl) = 'a' : succRevStr tl
succRevStr ( c :tl) = succ c : tl

succStr s =
    reverse . succRevStr . reverse $ s

groupCount s =
    let s' = group . sort $ s
    in  map (\l -> (head l, length l)) s'

main = do
    s <- getLine
    t <- getLine
    let sg = groupCount s
        tg = groupCount t

        searchLetter (c,n) =
          let x = case lookup c tg of
                    Nothing -> 0
                    Just x' -> x'
          in (x, n-x)

        counts = map searchLetter sg

        (yay,whoops) = foldl sumPair (0,0) counts
        sumPair (a,b) (a',b') = (a+a', b+b')

    putStrLn $ show yay ++ " " ++ show whoops


Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below.  So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted. The battery of the newest device allows to highlight at most n sections on the display. Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.

The first line contains the integer n (2 ≤ n ≤ 100 000) — the maximum number of sections which can be highlighted on the display.

Print the maximum integer which can be shown on the display of Stepan's newest device.

main = do x <- getLine
          if mod (read x) 2 == 1 then (sequence ((putStr "7"):[putStr "1" | i <- [1..(div (read x) 2)-1]])) >> putStrLn ""
          else sequence [putStr "1" | i <- [1..(div (read x) 2)]] >> putStrLn ""

f::Int -> [Char]
f n | mod n 2 == 0 = g (div n 2)
	| otherwise = '7' : g (div (n - 3) 2)

g::Int -> [Char]
g 0 = []
g n = '1' : g (n - 1)

main = getLine >>= (putStr . f . read . head . words)

fun :: Int -> String
fun 0 = ""
fun n
      | n `mod` 2 == 1    = "7" ++ (fun(n - 3))
      | True              = "1" ++ (fun(n - 2))

main = do
    inputjar <- getLine
    let n = read inputjar :: Int
    let temp = fun(n)
    putStr temp

f s n = concat $ replicate n s

g 0 a = f "1" a
g 1 a = concat ["7", (g 0 (a - 1))]

x a = (g (mod a 2) (div a 2))

main = do
	s <- getLine
	putStrLn (x (read s))

showNumbers :: Int -> IO ()
showNumbers 0 = return ()
showNumbers n =  if n `mod` 2 == 1
		then do
			putStr "7"
			showNumbers (n - 3)
		else do
			putStr "1"
			showNumbers (n - 2)

main :: IO ()
main = do
	str <- getLine
	let number = read str :: Int
	showNumbers number
	return ()

--ghc 7.10

import System.IO

import System.IO -- импорт  модуля IO

foo::Int -> String
foo n | even n = goo (n `div` 2)
      | otherwise = '7' : goo ((n `div` 2) - 1)

goo::Int -> String
goo 0 = []
goo n = '1' : goo (n-1)

main = do
       sx1 <- getLine
       --print (read (foo (read sx1 :: Int)) :: Int)
       putStrLn (foo (read sx1 :: Int))

import Data.Char
import Data.List

solve :: String -> IO ()

f :: Int -> String
f n
   | mod n 2 == 1	= '7' : (f (n - 3))
   | n == 0 = ""
   | otherwise = '1' : (f (n - 2))

solve = putStrLn . f . (read :: String -> Int)

main = getContents >>= solve

main = do
    n <- fmap read getLine :: IO Int
    putStrLn $ solve n

solve :: Int -> String
solve 2 = "1"
solve 3 = "7"
solve n
    | n `rem` 2 == 0 = '1' : solve (n - 2)
    | otherwise = '7' : solve (n - 3)

main = do
    n <- getLine
    putStrLn $ concat $ reverse $ calc $ (read n :: Int)
    where
        calc 0 = []
        calc 3 = ["7"]
        calc n = "1" : calc (n - 2)

solve :: Int -> String
solve x = let
    len = x `div` 2
    lans = replicate len '1'
  in if len * 2 == x then lans else '7':(tail lans)

main :: IO ()
main = do
  a <- getLine
  let x = read a :: Int
  putStrLn $ solve x

solve :: Integer -> Integer
solve x = let
    len = x `div` 2
    lans = ((10 ^ len) - 1) `div` 9
  in if len * 2 == x then lans else lans + 6 * 10 ^ (len - 1)

main :: IO ()
main = do
  a <- getLine
  let x = read a :: Integer
  print $ solve x

solve :: Int -> [Char]
solve t | t `mod` 2 == 0 = replicate (t `div` 2) '1'
		| otherwise = '7':(replicate ((t `div` 2) - 1) '1')

main = do
        t <- getLine
        putStrLn $ solve (read t :: Int)

main :: IO ()
main = do
  s <- readLn
  putStrLn $ segments s

segments :: Int -> String
segments n
  | n == 0 = ""
  | n `rem` 2 == 0 = "1" ++ segments (n - 2)
  | otherwise = "7" ++ segments (n - 3)

main = do
  line <- getLine
  let number = read line
  if number `mod` 2 == 0
  then putStrLn $ replicate (number `div` 2) '1'
  else putStrLn $ "7" ++ replicate ((number `div` 2) - 1) '1'

fun :: Int -> String
fun 0 = ""
fun n
      | n `mod` 2 == 1    = "7" ++ (fun(n - 3))
      | True              = "1" ++ (fun(n - 2))

main = do
    inputjar <- getLine
    let n = read inputjar :: Int
    let temp = fun(n)
    print (read temp :: Int)

fun :: Int -> String
fun 0 = ""
fun n
      | n `mod` 2 == 1    = "7" ++ (fun(n - 3))
      | True              = "1" ++ (fun(n - 2))

main = do
    inputjar <- getLine
    let n = read inputjar :: Int
    let temp = fun(n)
    print temp

--ghc 7.10

import System.IO

import System.IO -- импорт  модуля IO

foo::Int -> String
foo n | even n = goo (n `div` 2)
      | otherwise = '7' : goo ((n `div` 2) - 1)

goo::Int -> String
goo 0 = []
goo n = '1' : goo (n-1)

main = do
       sx1 <- getLine
       putStrLn $ show $ foo (read sx1 :: Int)

--ghc 7.10

import System.IO

import System.IO -- импорт  модуля IO

foo::Int -> String
foo n | even n = goo (n `div` 2)
      | otherwise = '7' : goo ((n `div` 2) - 1)

goo::Int -> String
goo 0 = []
goo n = '1' : goo (n-1)

main = do
       sx1 <- getLine
       print (read (foo (read sx1 :: Int)) :: Int)
       --putIntLn $ show $ read (foo (read sx1 :: Int)) :: Int

import Data.Char
import Data.List

solve :: String -> IO ()

f :: Int -> String
f n
   | n >= 4	= '1' : (f (n - 4))
   | n == 3 = "7"
   | n == 2 = "1"
   | otherwise = ""

solve = putStrLn . f . (read :: String -> Int)

main = getContents >>= solve

import Data.Char
import Data.List

solve :: String -> IO ()

f :: Int -> String
f n
   | n >= 4	= '1' : (f (n - 2))
   | n == 3 = "7"
   | n == 2 = "1"
   | otherwise = ""

solve = putStrLn . f . (read :: String -> Int)

main = getContents >>= solve

import Data.Char
import Data.List

solve :: String -> IO ()

f :: Int -> String
f n
   | n >= 6	= '9' : (f (n - 6))
   | n >= 3 = '7' : (f (n - 3))
   | n >= 2 = '1' : (f (n - 3))
   | otherwise = ""

solve = putStrLn . f . (read :: String -> Int)

main = getContents >>= solve

main = do
    n <- fmap read getLine :: IO Int
    putStrLn $ solve n

solve :: Int -> String
solve 2 = "1"
solve 3 = "7"
solve n = '1' : solve (n - 2)

main = do
    n <- getLine
    putStrLn $ concat $ calc $ (read n :: Int)
    where
        calc 0 = []
        calc 3 = ["7"]
        calc n = "1" : calc (n - 2)

solve :: Int -> Int
solve x = let
    len = x `div` 2
    lans = ((10 ^ len) - 1) `div` 9
  in if len * 2 == x then lans else lans + 6 * 10 ^ (len - 1)

main :: IO ()
main = do
  a <- getLine
  let x = read a :: Int
  print $ solve x


You have m = n·k wooden staves. The i-th stave has length ai. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel.Let volume vj of barrel j be equal to the length of the minimal stave in it.  You want to assemble exactly n barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed l, i.e. |vx - vy| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.Print maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.

The first line contains three space-separated integers n, k and l (1 ≤ n, k ≤ 105, 1 ≤ n·k ≤ 105, 0 ≤ l ≤ 109). The second line contains m = n·k space-separated integers a1, a2, ..., am (1 ≤ ai ≤ 109) — lengths of staves.

Print single integer — maximal total sum of the volumes of barrels or 0 if it's impossible to construct exactly n barrels satisfying the condition |vx - vy| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.

NoteIn the first example you can form the following barrels: [1, 2], [2, 2], [2, 3], [2, 3].In the second example you can form the following barrels: [10], [10].In the third example you can form the following barrels: [2, 5].In the fourth example difference between volumes of barrels in any partition is at least 2 so it is impossible to make barrels equal enough.

import Data.List
import Data.Int
main = do
    [[n, k, l], xs] <- fmap (map (map read . words) . lines) getContents
    let xx = sort xs
        ps = takeWhile (<= (head xx + l)) xx
        f 0 0 r _ = r
        f pr nr r ps@(pp:px) | pr - k >= nr - 1 = f (pr - k) (nr - 1) (p + r) (drop k ps)
                            | pr > nr = f (nr - 1) (nr - 1) (p + r) (drop (pr - nr) px)
                            | otherwise = f (nr - 1) (nr - 1) (p + r) px where p = fromIntegral pp
    print $ if length ps < n then 0 else f (length ps) n (0 :: Int64) ps

import Data.List
main = do
    [[n, k, l], xs] <- fmap (map (map read . words) . lines) getContents
    let xx = sort xs
        ps = takeWhile (<= (head xx + l)) xx
        f 0 0 r _ = r
        f pr nr r ps@(p:px) | pr - k >= nr - 1 = f (pr - k) (nr - 1) (p + r) (drop k ps)
                            | pr > nr = f (nr - 1) (nr - 1) (p + r) (drop (pr - nr) px)
                            | otherwise = f (nr - 1) (nr - 1) (p + r) px
    print $ if length ps < n then 0 else f (length ps) n 0 ps


Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ..., xr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the length of the arrays. The second line contains n integers ai (0 ≤ ai ≤ 109). The third line contains n integers bi (0 ≤ bi ≤ 109).

Print a single integer — the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n.

NoteBitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation.In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5.In the second sample, the maximum value is obtained for l = 1 and r = 9.

import Data.Bits
import Data.List

main :: IO ()
main = do
  c <- getContents
  let l = (map (read :: String -> Int) . words) c
  let n = head l
  let l1 = take n (tail l)
  let l2 = drop (n+1) l
  putStrLn $ show $ foldl' (.|.) 0 l1 + foldl' (.|.) 0 l2

module Main where

import Data.Complex
import Data.Char
import Data.List
import Data.Functor
import Data.Bits
import Control.Monad

type R = Double
type Z = Int
type B = Integer
type Q = Rational
type C = Complex

type A = Char
type S = String

readR = map read <$> words <$> getLine :: IO [R]
readR1 = head <$> readR

readZ = map read <$> words <$> getLine :: IO [Z]
readZ1 = head <$> readZ

readB = map read <$> words <$> getLine :: IO [B]
readB1 = head <$> readB

main :: IO ()
main = do
    getLine
    xs <- readZ
    ys <- readZ
    print $ (foldl1 (.|.)  xs) + (foldl1 (.|.) ys)

import Data.Bits

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

solve (n:ls) = foldl (.|.) 0 (take n ls) + foldl (.|.) 0 (drop n ls)

import Data.Bits
import Control.Monad

main :: IO ()
main = do
  _ <- getLine
  as <- liftM (map read . words) getLine
  bs <- liftM (map read . words) getLine
  print $ maxValue as + maxValue bs

maxValue :: [Integer] -> Integer
maxValue = foldl (.|.) 0

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

myread = read :: String -> Int
main = do
  _ <- getLine
  as <- map myread.words <$> getLine
  bs <- map myread.words <$> getLine
  print $ solve as bs

solve :: [Int] -> [Int] -> Int
solve as bs = foldl1 (.|.) as + foldl1 (.|.) bs

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

main = do
	getLine
	s1<-  foldl1 ((.|.)). map (  fst.fromJust.C.readInt) . C.words <$> C.getLine ::IO Int
	s2<-  foldl1 ((.|.)). map (  fst.fromJust.C.readInt) . C.words <$> C.getLine ::IO Int
	print $  s1 +  s2


Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, default values).Valery decided to examine template procedures in this language in more detail. The description of a template procedure consists of the procedure name and the list of its parameter types. The generic type T parameters can be used as parameters of template procedures.A procedure call consists of a procedure name and a list of variable parameters. Let's call a procedure suitable for this call if the following conditions are fulfilled:   its name equals to the name of the called procedure;  the number of its parameters equals to the number of parameters of the procedure call;  the types of variables in the procedure call match the corresponding types of its parameters. The variable type matches the type of a parameter if the parameter has a generic type T or the type of the variable and the parameter are the same. You are given a description of some set of template procedures. You are also given a list of variables used in the program, as well as direct procedure calls that use the described variables. For each call you need to count the number of procedures that are suitable for this call.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of template procedures. The next n lines contain the description of the procedures specified in the following format: "void procedureName (type_1, type_2, ..., type_t)" (1 ≤ t ≤ 5), where void is the keyword, procedureName is the procedure name, type_i is the type of the next parameter. Types of language parameters can be "int", "string", "double", and the keyword "T", which denotes the generic type. The next line contains a single integer m (1 ≤ m ≤ 1000) — the number of used variables. Next m lines specify the description of the variables in the following format: "type variableName", where type is the type of variable that can take values "int", "string", "double", variableName — the name of the variable. The next line contains a single integer k (1 ≤ k ≤ 1000) — the number of procedure calls. Next k lines specify the procedure calls in the following format: "procedureName (var_1, var_2, ..., var_t)" (1 ≤ t ≤ 5), where procedureName is the name of the procedure, var_i is the name of a variable. The lines describing the variables, template procedures and their calls may contain spaces at the beginning of the line and at the end of the line, before and after the brackets and commas. Spaces may be before and after keyword void. The length of each input line does not exceed 100 characters. The names of variables and procedures are non-empty strings of lowercase English letters and numbers with lengths of not more than 10 characters. Note that this is the only condition at the names. Only the specified variables are used in procedure calls. The names of the variables are distinct. No two procedures are the same. Two procedures are the same, if they have identical names and identical ordered sets of types of their parameters.

On each of k lines print a single number, where the i-th number stands for the number of suitable template procedures for the i-th call.

4
void f(int,T)
void  f(T, T)
 void foo123   ( int,  double,  string,string  )
  void  p(T,double)
3
int a
 string    s
double x123
5
f(a,  a)
  f(s,a   )
foo   (a,s,s)
 f  (  s  ,x123)
proc(a)

6
void f(string,double,int)
void f(int)
   void f  ( T  )
void procedure(int,double)
void f  (T, double,int)
void f(string, T,T)
4
 int a
 int x
string  t
double  val
5
f(t, a, a)
f(t,val,a)
f(val,a, val)
 solve300(val, val)
f  (x)

import Data.Map (fromList, findWithDefault)

data Type = T | TInt | TString | TDouble
    deriving (Show)
data Signature = Signature String [Type]
    deriving (Show)

instance Eq Type where
    T == _ = True
    _ == T = True
    TInt == TInt = True
    TString == TString = True
    TDouble == TDouble = True
    _ == _ = False

instance Eq Signature where
    (Signature name1 params1) == (Signature name2 params2) = name1 == name2 && params1 == params2

readType "T" = T
readType "int" = TInt
readType "string" = TString
readType "double" = TDouble
readType s = error s

wordsBy dels s = wordsBy' $ dropWhile p s
    where
        p = flip elem dels
        wordsBy' "" = []
        wordsBy' s = (takeWhile (not . p) s):(wordsBy' $ dropWhile p $ dropWhile (not . p) s)

main = do
    n <- fmap read getLine
    signs <- fmap (map ((\(_:name:params) -> Signature name $ map readType params) . wordsBy [' ', ',', '(', ')'])) $ sequence $ replicate n getLine
    m <- fmap read getLine
    vars <- fmap (map ((\([t,name]) -> (name, readType t)) . words)) $ sequence $ replicate m getLine
    let mvars = fromList vars
    k <- fmap read getLine
    calls <- fmap (map ((\(name:params) -> Signature name $ map (\var -> findWithDefault T var mvars) params) . wordsBy [' ', ',', '(', ')'])) $ sequence $ replicate k getLine
    mapM_ (\call -> print $ length $ filter (== call) signs) calls

import Data.Char
import Data.Map (Map,(!))
import qualified Data.Map as M
import Control.Applicative
import Control.Monad

main = do
  n <- readLn
  procm <- parseProc <$> replicateM n getLine
  m <- readLn
  varm <- parseVar <$> replicateM m getLine
  k <- readLn
  calls <- replicateM k getLine
  putStr.unlines.map (show.solve procm varm.parseCall) $ calls

solve :: [(String,[TT])] -> Map String TT -> (String,[String]) -> Int
solve procs varm (name,vars) = length [(n,ts)|(n,ts)<-procs,n==name,match ts types]
   where
     types :: [TT]
     types = map (varm!) vars

data TT = I | S | D | T deriving Eq

(#) :: TT -> TT -> Bool
_#T = True
T#_ = True
x#y = x==y

match :: [TT] -> [TT] -> Bool
match xs ys = lx==ly && and (zipWith (#) xs ys)
   where
     lx = length xs
     ly = length ys

toTT :: String -> TT
toTT "int" = I
toTT "string" = S
toTT "double" = D
toTT "T" = T

parseProc :: [String] -> [(String,[TT])]
parseProc ss = map parse ss
   where
     f ',' = ' '
     f c = c
     parse cs = let (name,'(':xs) = break ('('==).filter(not.isSpace).drop 4.dropWhile isSpace $ cs
                    types = map toTT.words.map f.init $ xs
                in (name,types)

parseVar :: [String] -> Map String TT
parseVar ss = M.fromList $ map parse ss
   where
     parse cs = let (t,xs) = span isAlphaNum.dropWhile isSpace $ cs
                    var = filter isAlphaNum xs
                in (var,toTT t)

parseCall :: String -> (String,[String])
parseCall cs = let (name,'(':xs) = break ('('==).filter(not.isSpace) $ cs
                   f ',' = ' '
                   f c = c
                   vars = words.map f.init $ xs
               in (name,vars)


Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows:  Pasha can boil the teapot exactly once by pouring there at most w milliliters of water;  Pasha pours the same amount of water to each girl;  Pasha pours the same amount of water to each boy;  if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.

The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters.

Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

NotePasha also has candies that he is going to give to girls but that is another task...

 -- http://codeforces.com/problemset/problem/557/B
 -- TODO: Program exceeds time!

-- Faster if we read from ByteString
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe
import qualified Numeric as N

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

main = do

	line <-
		fmap (map (fst . fromJust))
		$ fmap (map B.readInt)
		$ fmap B.words
		$ B.getLine
	cups <-
		fmap (map fromIntegral)
		$ fmap sort
		$ fmap (map (fst . fromJust))
		$ fmap (map B.readInt)
		$ fmap B.words
		$ B.getLine

	let
		ni:wi:_ = line
		(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)
		min1 = min (head cups) ((cups !! ni) / 2)
		min2 = min min1 (w / (3 * n))
		ans = min2 * (3 * n)

	putStrLn $ N.showFFloat Nothing (ans) ""
	return ()

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

main= do
	[n,w]<-  map read.words <$> getLine ::IO [Int]
	s<- sort . map (fst.fromJust.C.readInt). C.words <$> C.getLine :: IO [Int]
	let m = head s
	let m1 = head ( drop n s)
	let sm = if (m *2 <=m1) then   (fromIntegral m) else   (fromIntegral m1)/2.0
	print $ min (fromIntegral w) (sm *3.0*(fromIntegral n))

 -- http://codeforces.com/problemset/problem/557/B
 -- TODO: Program exceeds time!

-- Faster if we read from ByteString
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe
import qualified Numeric as N

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

main = do

	line <-
		fmap (map (fst . fromJust))
		$ fmap (map B.readInt)
		$ fmap B.words
		$ B.getLine
	cups <-
		fmap (map fromIntegral)
		$ fmap sort
		$ fmap (map (fst . fromJust))
		$ fmap (map B.readInt)
		$ fmap B.words
		$ B.getLine

	let
		ni:wi:_ = line
		(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)
		boys = min (cups !! ni) ( (w/(3*n)) * 2 )
		girls = min (head cups) (boys / 2)

	putStrLn $ N.showFFloat Nothing (girls*n + boys*n) ""
	return ()

import Data.List

clamp :: (Num a, Eq a, Ord a) => a -> a -> a -> a
clamp val lower upper = min upper (max val lower)

main = do

	line <- getLine
	cups <- getLine

	let
		n:ml:_ = map read $ words line :: [Int]
		nf = fromIntegral n
		cs = sort $ take (2*n) $ map read $ words cups :: [Float]
		max_boys = head $ take n $ drop n cs
		max_girls = clamp (head $ take n cs) 0 (max_boys / 2)

	putStrLn $ show $ (nf*max_boys + nf*max_girls)

	return ()

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

-- pour :: Float -> Int -> Int -> Float -> Float -> Float
-- pour has boys girls pour_boys pour_girls
-- 	| total_pour <= has= 10**(-6) = boys*pour_boys + girls*pour_girls
-- 	|

 -- http://codeforces.com/problemset/problem/557/B
 -- TODO: Program exceeds time!

-- Faster if we read from ByteString
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe

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

main = do

	line <- fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words $ B.getLine
	cups <- fmap (map fromIntegral) $ fmap sort $ fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words $ B.getLine

	let
		ni:wi:_ = line
		(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)
		girls1 = min (head cups) ((cups !! ni) / 2)
		girls2 = min girls1 (w / 3 * n)
		girls3 = girls2 * 3 * n

	putStrLn $ show girls3
	return ()

 -- http://codeforces.com/problemset/problem/557/B
 -- TODO: Program exceeds time!

-- Faster if we read from ByteString
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe
import qualified Numeric as N

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

main = do

	line <-
		fmap (map (fst . fromJust))
		$ fmap (map B.readInt)
		$ fmap B.words
		$ B.getLine
	cups <-
		fmap (map fromIntegral)
		$ fmap sort
		$ fmap (map (fst . fromJust))
		$ fmap (map B.readInt)
		$ fmap B.words
		$ B.getLine

	let
		ni:wi:_ = line
		(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)
		boys = min (cups !! ni) ( ((w / 3) * 2) / n )
		girls = min (head cups) (boys / 2)

	putStrLn $ N.showFFloat Nothing (girls*n + boys*n) ""
	return ()

 -- http://codeforces.com/problemset/problem/557/B
 -- TODO: Program exceeds time!

-- Faster if we read from ByteString
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe

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

main = do

	line <-
		fmap (map (fst . fromJust))
		$ fmap (map B.readInt)
		$ fmap B.words
		$ B.getLine
	cups <-
		fmap (map fromIntegral)
		$ fmap sort
		$ fmap (map (fst . fromJust))
		$ fmap (map B.readInt)
		$ fmap B.words
		$ B.getLine

	let
		ni:wi:_ = line
		(n, w) = (fromIntegral ni, fromIntegral wi) :: (Double, Double)
		boys = min (cups !! ni) ( ((w / 3) * 2) / n )
		girls = min (head cups) (boys / 2)

	putStrLn $ show $ girls*n + boys*n
	return ()

import Data.List

clamp :: (Num a, Eq a, Ord a) => a -> a -> a -> a
clamp val lower upper = min upper (max val lower)

main = do

	line <- getLine
	cups <- getLine

	let
		nf:ml:_ = map read $ words line :: [Float]
		n = truncate nf
		cs = sort $ take (2*n) $ map read $ words cups :: [Float]
		max_boys = clamp (head $ take n $ drop n cs) 0 (2 * ml / 3)
		max_girls = clamp (head $ take n cs) 0 (max_boys / 2)

	putStrLn $ show $ (nf*max_boys + nf*max_girls)

	return ()

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

-- pour :: Float -> Int -> Int -> Float -> Float -> Float
-- pour has boys girls pour_boys pour_girls
-- 	| total_pour <= has= 10**(-6) = boys*pour_boys + girls*pour_girls
-- 	|

import Control.Applicative
import Data.List

main= do
	[n,w]<-  map read.words <$> getLine ::IO [Int]
	s<- sort . map read. words <$> getLine :: IO [Int]
	let m = head s
	let m1 = head ( drop n s)
	let sm = if (m *2 <=m1) then   (fromIntegral m) else   (fromIntegral m1)/2.0
	print $ sm *3.0


Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1, a2, ..., an.While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b1, b2, ..., bn. Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way).Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.

The first line contains three integers n, l, r (1 ≤ n ≤ 105, 1 ≤ l ≤ r ≤ n) — the number of Vasya's cubes and the positions told by Stepan. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ n) — the sequence of integers written on cubes in the Vasya's order. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ n) — the sequence of integers written on cubes after Stepan rearranged their order. It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes.

Print "LIE" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print "TRUTH" (without quotes).

NoteIn the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]).In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother.In the third example for any values l and r there is a situation when Stepan said the truth.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

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

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

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

main = do
	[ n, l , r ] <- readInts
	aa <- getList
	bb <- getList

	let as = [1] ++ aa ++ [1]
	let bs = [1] ++ bb ++ [1]

	--d <- [l-1,r-l+1,n-r]
	--print $d
	let [al , am , ar] = splitPlaces [l, r-l+1, n-r+1] as
	let [bl , bm , br] = splitPlaces [l, r-l+1, n-r+1] bs

	let bam = sort bm
	let sam = sort am

	let a = al ++ sam ++ ar
	let b = bl ++ bam ++ br

	let x = which "TRUTH" "LIE" (a==b)

	putStrLn $x

	--print $ (as==bs)
	--print $ ( `div` 2 ) $ succ $ sum $ map ( \m -> ( m + k - 1 ) `div` k ) as

import Data.List (sort)
main = do
  (n:l:r:as) <- fmap (map read . words) getContents
--   let ks = (sort as) !! (n-k)
--   print . length . filter (> 0) $ as
  let (a, b) = splitAt n as

  let (al, _) = (splitAt (l - 1) a)
  let (_, ar) = (splitAt r a)

  let (bl, _) = (splitAt (l - 1) b)
  let (_, br) = (splitAt r b)

  let (_, arp) = (splitAt (l - 1) a)
  let (ai, _) = (splitAt (r - l + 1) arp)

  let (_, brp) = (splitAt (l - 1) b)
  let (bi, _) = (splitAt (r - l + 1) brp)

  let ais = sort ai
  let bis = sort bi

  let res = if (ais == bis) && (al == bl) && (ar == br)
        then "TRUTH"
        else "LIE"

  putStrLn res

solve :: Int -> Int -> [Int] -> [Int] -> String
solve l r [] [] = "TRUTH"
solve l r (a:as) (b:bs)
    | (l > 0 || r < 0) && a /= b = "LIE"
    | otherwise = solve (l-1) (r-1) as bs

main = do
    [n,l,r] <- fmap (fmap read) $ fmap words $ getLine
    as <- fmap (fmap read) $ fmap words $ getLine
    bs <- fmap (fmap read) $ fmap words $ getLine
    putStrLn $ solve (l-1) (r-1) as bs

module Main where

import Data.List (sort)
import Data.Functor((<$>))

main = do
    [n, l', r] <- map readInt . words <$> getLine
    a <- map readInt . words <$> getLine
    b <- map readInt . words <$> getLine
    let l = l' - 1
        am = take (r - l) . drop l $ a
        bm = take (r - l) . drop l $ b
    if (take l a == take l b && drop r b == drop r a && sort am == sort bm)
        then putStrLn "TRUTH"
        else putStrLn "LIE"
    return ()

readInt :: String -> Int
readInt = read

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

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

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

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

main = do
	[ n, l , r ] <- readInts
	as <- getList
	bs <- getList

	--d <- [l-1,r-l+1,n-r]
	--print $d
	let [al , am , ar] = splitPlaces [l-1, r-l+1, n-r] as
	let [bl , bm , br] = splitPlaces [l-1, r-l+1, n-r] bs

	let bam = sort bm
	let sam = sort am

	let a = al ++ sam ++ ar
	let b = bl ++ bam ++ br

	let x = which "TRUTH" "LIE" (a==b)

	print $x

	--print $ (as==bs)
	--print $ ( `div` 2 ) $ succ $ sum $ map ( \m -> ( m + k - 1 ) `div` k ) as

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

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

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

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

main = do
	[ n, l , r ] <- readInts
	as <- getList
	bs <- getList

	let as = [1] ++ as ++ [1]
	let bs = [1] ++ bs ++ [1]

	--d <- [l-1,r-l+1,n-r]
	--print $d
	let [al , am , ar] = splitPlaces [l, r-l+1, n-r+1] as
	let [bl , bm , br] = splitPlaces [l, r-l+1, n-r+1] bs

	let bam = sort bm
	let sam = sort am

	let a = al ++ sam ++ ar
	let b = bl ++ bam ++ br

	let x = which "TRUTH" "LIE" (a==b)

	putStrLn $x

	--print $ (as==bs)
	--print $ ( `div` 2 ) $ succ $ sum $ map ( \m -> ( m + k - 1 ) `div` k ) as


Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.

The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane.  Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide.

In the first line print an integer — the number of triangles with the non-zero area among the painted points.

NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle.

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

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

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

main = do
  n <- readLn
  ps <- replicateM n $ (\[x, y] -> (x, y)) <$> getInts

  let
    count n = n'*(n'-1)*(n'-2) `div` 6 where n' = fromIntegral n :: Int64
    count2 n = n'*(n'-1) `div` 2 where n' = fromIntegral n :: Int64

    r = count n - (sum $ map f $ init $ tails ps)
      where
        f ((x, y):ps) = sum vs
          where
            vs = map (count2 . length) $ group $ sort $ map norm $ map (\(xx, yy) -> (xx-x, yy-y)) ps
              where
                norm (x, y) = (x' `div` d, y' `div` d)
                  where
                    (x', y') = if x < 0 || x == 0 && y < 0 then (-x, -y) else (x, y)
                    d = gcd x y

  print r

import Control.Exception.Base
import Debug.Trace
import Data.Functor
import Data.List

readInts :: IO [Int]
readInts = map read <$> words <$> getContents
parsePairs :: [Int] -> [(Int, Int)]
parsePairs [] = []
parsePairs (x:y:rs) = (x, y) : parsePairs rs

main = readInts >>= putStrLn . show . solve . parsePairs . tail

solve :: [(Int, Int)] -> Integer
solve rs = let n = toInteger $ length rs in n * (n-1) * (n-2) `div` 6 - countDegen rs

countDegen :: [(Int, Int)] -> Integer
countDegen = f . sort where
    f [] = 0
    f (r:[]) = 0
    f ((x0, y0):rs) = go (map (\(x, y) -> (x-x0, y-y0)) rs) + f rs

simplify (x, y)
    | x == 0 = (0, 1)
    | y == 0 = (1, 0)
    | otherwise = let g = gcd x y in f (div x g) (div y g)
    where f x y = if x > 0 then (x, y) else (-x, -y)

go = sum . map (pairs . length) . group . sort . map simplify
    where pairs x = toInteger $ x * (x - 1) `div` 2

import Control.Exception.Base
import Debug.Trace
import Data.Functor
import Data.List

readInts :: IO [Int]
readInts = map read <$> words <$> getContents
parsePairs :: [Int] -> [(Int, Int)]
parsePairs [] = []
parsePairs (x:y:rs) = (x, y) : parsePairs rs

main = readInts >>= putStrLn . show . solve . parsePairs . tail

solve :: [(Int, Int)] -> Integer
solve rs = let n = toInteger $ length rs in n * (n-1) * (n-2) `div` 6 - countDegen rs

countDegen :: [(Int, Int)] -> Integer
countDegen = f . sort where
    f [] = 0
    f (r:[]) = 0
    f (r:rs) = go r rs + f rs

geoMult :: Num a => (a, a) -> (a, a) -> (a, a) -> a
geoMult (x0, y0) (x1, y1) (x2, y2) = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)

go center rs = sum $ map (f . length) $ groupBy (\x y -> cmp center x y == EQ) $ sortBy (cmp center) rs
    where f x = toInteger $ x * (x - 1) `div` 2

cmp center x y
    | r < 0 = LT
    | r > 0 = GT
    | r == 0 = EQ
    where r = geoMult center x y

import Data.List (group, sort)
import Control.Applicative ((<$>), liftA)
import Control.Monad (replicateM)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8

parse :: ByteString -> (Int, Int)
parse = (\(Just [a, b]) -> (a, b)). sequence . fmap readInt . B8.words
    where
    readInt :: ByteString -> Maybe Int
    readInt = (liftA fst) . B8.readInt

f :: Int -> Int
f n = n * (n - 1) `div` 2

tria :: Int -> [(Int, Int)] -> Int
tria acc [] = acc
tria acc [(x, y)] = acc
tria acc ((x,y):rest) = tria acc' rest
    where
    n = length rest :: Int
    a = fmap length . group . sort . fmap slope $ rest :: [Int]

    acc' = acc + f n - (sum . fmap f $ a) :: Int

    slope :: (Int, Int) -> (Int, Int)
    slope (u, v)
        | u == x = (0, 1)
        | v == y = (1, 0)
        | otherwise = (dx `div` w', dy `div` w')
        where
        dx = x - u :: Int
        dy = y - v :: Int
        w = gcd dx dy :: Int
        w' = if (dx < 0) == (w < 0) then w else (-w) :: Int

main = read <$> getLine >>= \n ->
    tria 0 . fmap parse <$> replicateM n B.getLine >>= print

import Data.List (group, sort)

data Point = Point Int Int
             deriving (Show, Eq)
type Input = [Point]

parse :: String -> Input
parse = map (parsePoint . map read . words) . lines
        where parsePoint [x, y] = Point x y
              parsePoint _      = undefined

instance Ord Point where
    (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'

normalize :: Int -> Int -> Point
normalize 0 0 = Point 0 0
normalize x y
    | invalid   = normalize (-x) (-y)
    | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)
    where invalid = y < 0 || y == 0 && x < 0

pairs :: Int -> Int
pairs n = n * (n - 1) `div` 2

colinears :: [Point] -> Int
colinears = sum . map (pairs . length) . group . sort

solve' :: Point -> [Point] -> Int
solve' (Point x0 y0) ps' = pairs (n - 1) - colinears ps
                           where n  = length ps
                                 ps = map (\(Point x y) -> normalize (x - x0) (y - y0)) ps'

solve :: Input -> Integer
solve ps = sum [fromIntegral (solve' p ps) | p <- ps] `div` 3

main :: IO ()
main = do
       _ <- getLine
       print . solve . parse =<< getContents

import Data.List (group, sort)

data Point = Point Int Int
             deriving (Show, Eq)
type Input = [Point]

parse :: String -> Input
parse = map (parsePoint . map read . words) . lines
        where parsePoint [x, y] = Point x y
              parsePoint _      = undefined

instance Ord Point where
    (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'

normalize :: Point -> Point
normalize p@(Point 0 0) = p
normalize (Point x y)
    | invalid         = normalize (Point (-x) (-y))
    | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)
    where invalid = y < 0 || y == 0 && x < 0

solve' :: Point -> [Point] -> Int
solve' (Point x0 y0) ps' = pairs (length ps - 1) - colineras
                           where ps = map f ps'
                                 f (Point x y) = normalize (Point (x - x0) (y - y0))
                                 colineras = sum . map (pairs . length) . group . sort $ ps
                                 pairs n = n * (n - 1) `div` 2

solve :: Input -> Integer
solve ps = sum [fromIntegral (solve' p ps) | p <- ps] `div` 3

main :: IO ()
main = do
       _ <- getLine
       print . solve . parse =<< getContents

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

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

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

main = do
  n <- readLn
  ps <- replicateM n $ (\[x, y] -> (x, y)) <$> getInts

  let
    count n = n'*(n'-1)*(n'-2) `div` 6 where n' = fromIntegral n :: Int64

    r = count n - (sum $ map f $ init $ tails ps)
      where
        f ((x, y):ps) = sum vs
          where
            vs = map (count . (+1) . length) $ group $ sort $ map norm $ map (\(xx, yy) -> (xx-x, yy-y)) ps
              where
                norm (x, y) = (x' `div` d, y' `div` d)
                  where
                    (x', y') = if x < 0 || x == 0 && y < 0 then (-x, -y) else (x, y)
                    d = gcd x y

  print r

import Data.List (group, sort)

data Point = Point Int Int
             deriving (Show, Eq)
type Input = [Point]

parse :: String -> Input
parse = map (parsePoint . map read . words) . lines
        where parsePoint [x, y] = Point x y
              parsePoint _      = undefined

instance Ord Point where
    (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'

normalize :: Point -> Point
normalize p@(Point 0 0) = p
normalize (Point x y)
    | invalid         = normalize (Point (-x) (-y))
    | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)
    where invalid = y < 0 || y == 0 && x < 0

solve' :: Point -> [Point] -> Int
solve' (Point x0 y0) ps' = pairs (length ps - 1) - colineras
                           where ps = map f ps'
                                 f (Point x y) = normalize (Point (x - x0) (y - y0))
                                 colineras = sum . map (pairs . length) . group . sort $ ps
                                 pairs n = n * (n - 1) `div` 2

solve :: Input -> Int
solve ps = sum [solve' p ps | p <- ps] `div` 3

main :: IO ()
main = do
       _ <- getLine
       print . solve . parse =<< getContents


There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1 ≤ i ≤ n - 1), such that ai + 1 > ai.

The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of painting. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai means the beauty of the i-th painting.

Print one integer — the maximum possible number of neighbouring pairs, such that ai + 1 > ai, after the optimal rearrangement.

NoteIn the first sample, the optimal order is: 10, 20, 30, 40, 50.In the second sample, the optimal order is: 100, 200, 100, 200.

import Data.List

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

solve :: [Int] -> Int
solve a = solve' (sort a) [] []

solve' :: [Int] -> [Int] -> [Int] -> Int
solve' [] [] [] = 0
solve' [] curr next = (length curr) - 1 + solve' (reverse next) [] []
solve' (a:ax) [] [] = solve' ax [a] []
solve' (a:ax) (c:cx) next | a == c = solve' ax (c:cx) (a:next)
                          | otherwise = solve' ax (a:c:cx) next

import Data.List

main::IO ()
main = getLine >> do
  us <- fmap (map read. words) getLine :: IO [Int]
  print $ snd $ foldl' go (Nothing, 0::Int) $ sort us where
    go (Nothing , acc) el   = (Just (el, 1::Int, 0::Int), acc)
    go (Just (p, reps, racc), acc) el
      | p == el && racc > 0 = (Just (el, reps + 1, racc - 1), acc + 1)
      | p == el             = (Just (el, reps + 1, racc    ), acc)
      | otherwise           = (Just (el, 1, racc + reps - 1), acc + 1)

module Main where

import Data.Complex
import Data.Char
import Data.List
import Data.Functor
import Control.Monad

type R = Double
type Z = Int
type B = Integer
type Q = Rational
type C = Complex

type A = Char
type S = String

readR = map read <$> words <$> getLine :: IO [R]
readR1 = head <$> readR

readZ = map read <$> words <$> getLine :: IO [Z]
readZ1 = head <$> readZ

readB = map read <$> words <$> getLine :: IO [B]
readB1 = head <$> readB

g :: (Ord a) => [a] -> [[a]]
g [x] = [[x]]
g (x:xs)
    | x < head y = (x : y) : ys
    | otherwise = [x] : zs
    where zs@(y:ys) = g xs

f :: (Ord a) => [[a]] -> [[a]]
f [] = []
f xs = h xs (length xs)
    where
    h (y:ys) n
        | m == n = zs
        | otherwise = h zs m
        where
        zs = f' y ys
        m = length zs
    f' y [] = [y]
    f' y zs'@(z:zs)
        | last y < head z = (y ++ z) : zs
        | otherwise = z : f' y zs

main :: IO ()
main = do
    _ <- readZ1
    xs <- readZ
    print $ sum . map (\x -> length x - 1) . f . g . sort $ xs

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE TupleSections #-}

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function
import           Data.Array
-- import           Data.Array.ST
-- import           Data.Array.Unsafe
import           Data.Maybe
import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))
-- import qualified Data.Sequence as S

out = stdout

main = do
  _ <- readInt1 <$> BS.getLine
  ns <- readIntN <$> BS.getLine
  print $ solve ns

solve :: [Int] -> Int
solve = sum . map (pred.length) . transpose . group . sort where

-- makeTable :: -> Table
-- makeTable

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

readInt1 :: BS.ByteString -> Int
readInt1 = fst . fromJust . BS.readInt

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readIntN

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readIntN

readIntN :: BS.ByteString -> [Int]
readIntN =  map readInt1 . BS.words

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

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

fromTuple :: (a, a) -> [a]
fromTuple (x, y) = [x, y]

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

-- if not applying, use "const"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)

-- output functions

data Cell  = ByteStringC BL.ByteString
           | IntC Int
           | Int64C Int64
           deriving( Eq, Ord, Show )

data Row   = ListR [Cell]
           | TupleR (Cell,Cell)
           | TripleR (Cell,Cell,Cell)
           deriving( Eq, Ord, Show )

type Table = [Row]

infixr 4 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend

putAns :: Handle -> Table -> IO ()
putAns o = hPutBuilder o . renderTable

renderTable :: Table -> Builder
renderTable rs = mconcat [renderRow r <> char8 '\n' | r <- rs]

renderRow :: Row -> Builder
renderRow (ListR []) = mempty
renderRow (ListR (c:cs)) = renderCell c <> mconcat [ char8 ' ' <> renderCell c' | c' <- cs ]
renderRow (TupleR (x,y)) = renderCell x <> char8 ' ' <> renderCell y
renderRow (TripleR (x,y,z)) = renderCell x <> char8 ' ' <> renderCell y <> char8 ' ' <> renderCell z

renderCell :: Cell -> Builder
renderCell (ByteStringC cs) = lazyByteString cs
renderCell (IntC i) = intDec i
renderCell (Int64C i) = int64Dec i

import Data.List

solve :: [Int] -> Int
solve xs = (length xs) - (maximum $ map length $ group $ sort xs)

main = print . solve . map read . words . head . tail . lines =<< getContents

import Control.Applicative

main = (words <$> getLine) >>= print


To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i<j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i<j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i < j \le n$$$.

The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).

Output the single number — $$$\prod_{1\le i<j\le n} |a_i - a_j| \bmod m$$$.

NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.

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

main = do
  (n:m:_) <- map read.words <$> getLine
  as <- map read.words <$> getLine
  if any (> 1) $ map length $ group $ sort $ map (`mod` m) as
    then print 0
    else print $ foldr (\a b -> (a * b) `mod` m) 1 [abs (ai - aj) `mod` m | i <- [0..n - 1], let (pre, (aj:_)) = genericSplitAt i as, ai <- pre]

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Char
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 Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

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

main_ :: EIO ()
-- template --
main_ = do
    (n, m) <- liftM2 (,) get get
    a <- replicateM n get
    putln $ f1 a n m

f1 :: [Int64] -> Int -> Int -> Int64
f1 a n m =  if n >= m + 1
            then 0
            else let aa = array (1, length a) (zip [1..length a] a) :: UArray Int Int64 in
                foldl (\s i ->
                    foldl (\s j ->
                        (mod (s * (abs ((aa ! i) - (aa ! j)))) (fromIntegral m))
                    ) s [i+1..length a]
                ) 1 [1..length a]

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

main = do
  (n:m:_) <- map read.words <$> getLine
  as <- map read.words <$> getLine
  if any (> 1) $ map length $ group $ sort $ map (`mod` m) as
    then print 0
    else print $ product [abs (ai - aj) `mod` m | i <- [0..n - 1], let (pre, (aj:_)) = splitAt i as, ai <- pre] `mod` m

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

main = do
  (n:m:_) <- map read.words <$> getLine
  as <- map read.words <$> getLine
  if any (> 1) $ map length $ group $ sort $ map (`mod` m) as
    then print 0
    else print $ product [abs $ ai - aj | i <- [0..n - 1], let (pre, (aj:_)) = splitAt i as, ai <- pre] `mod` m

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Char
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 Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

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

main_ :: EIO ()
-- template --
main_ = do
    (n, m) <- liftM2 (,) get get
    a <- replicateM n get
    putln $ f1 a n m

f1 :: [Int64] -> Int -> Int -> Int64
f1 a n m =  if n + 1 >= m
            then 0
            else let aa = array (1, length a) (zip [1..length a] a) :: UArray Int Int64 in
                foldl (\s i ->
                    foldl (\s j ->
                        (mod (s * (abs ((aa ! i) - (aa ! j)))) (fromIntegral m))
                    ) s [i+1..length a]
                ) 1 [1..length a]


Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer ai — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will definitely wake up if during some m consecutive minutes at least k alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time.Vitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on.

First line contains three integers n, m and k (1 ≤ k ≤ n ≤ 2·105, 1 ≤ m ≤ 106) — number of alarm clocks, and conditions of Vitalya's waking up.  Second line contains sequence of distinct integers a1, a2, ..., an (1 ≤ ai ≤ 106) in which ai equals minute on which i-th alarm clock will ring. Numbers are given in arbitrary order. Vitalya lives in a Berland in which day lasts for 106 minutes.

Output minimal number of alarm clocks that Vitalya should turn off to sleep all next day long.

NoteIn first example Vitalya should turn off first alarm clock which rings at minute 3.In second example Vitalya shouldn't turn off any alarm clock because there are no interval of 10 consequence minutes in which 3 alarm clocks will ring.In third example Vitalya should turn off any 6 alarm clocks.

module Main where
import qualified Data.ByteString.Char8 as B
import Data.List
import qualified Data.Sequence as S
import Data.Array.Unboxed

main = B.interact exec
exec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . B.words
solve (n:m:k:xs0) = sum $ snd $ mapAccumL (\q ((l, _), (r, o)) -> let q' = (if o then (S.|> r) else id) $ S.dropWhileL (< l) q in if S.length q' >= k then (S.take (k - 1) q', S.length q' - k + 1) else (q', 0)) (S.fromList $ map fst $ filter snd ps) $ zip (tail xs) rs
  where
  xs = assocs (accumArray (flip const) False (0, hi) $ zip xs0 (repeat True) :: UArray Int Bool)
  (ps, rs) = splitAt m xs
  hi = 10^6

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

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import qualified Data.List as L (sort)
import qualified Data.Sequence as Q ((|>), viewl, viewr, ViewL((:<)), ViewR((:>)), empty, length)

readInt = fst . M.fromJust . C.readInt

run m k s [] ans = ans
run m k s (x:xs) ans = run m k rs xs r where
    ns = niter (s Q.|> x)
    niter ns@(Q.viewl -> l Q.:< ls) | x - l >= m = niter ls | otherwise = ns
    aiter ans (Q.length -> 0) = (ans, Q.empty)
    aiter ans ns@(Q.viewr -> rs Q.:> r) | Q.length ns >= k = aiter (ans + 1) rs | otherwise = (ans, ns)
    (r, rs) = aiter ans ns

main = do
    (map readInt . C.words -> [n, m, k]) <- B.getLine
    (L.sort . map readInt . C.words -> xs) <- B.getLine
    putStrLn $ show $ run m k Q.empty xs 0


As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 ≤ fi ≤ n and fi ≠ i.We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.

The first line contains a single integer n (2 ≤ n ≤ 5000) — the number of planes. The second line contains n integers f1, f2, ..., fn (1 ≤ fi ≤ n, fi ≠ i), meaning that the i-th plane likes the fi-th.

Output «YES» if there is a love triangle consisting of planes on Earth. Otherwise, output «NO». You can output any letter in lower case or in upper case.

NoteIn first example plane 2 likes plane 4, plane 4 likes plane 1, plane 1 likes plane 2 and that is a love triangle.In second example there are no love triangles.

import Data.List
import qualified Data.Map as Map
f::Map.Map Int Int->Int->Bool
f ms x=let Just x1=Map.lookup x ms
           Just x2=Map.lookup x1 ms
           Just x3=Map.lookup x2 ms
       in if x==x3 then True else False

main = do
       a<-getLine
       b<-getLine
       let e=read a::Int
           xs=map read (words b)::[Int]
           ms=Map.fromList $ zip [1..e] xs
       putStrLn $ if (any (==True ) ( map (f ms) xs))==True then "YES" else "NO"

import Data.Array
main = interact $ solve . map read . words
solve (n:as) | any (\i -> g!(g!(g!i)) == i) (indices g) = "YES" | otherwise = "NO"
  where g = listArray (1,n) as

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array
import qualified Data.Map as M

check n lk x | n>lk = False
             | n /=t1 && t1 /=t2 && t2 /=t3 && t3==n =True
	     | otherwise = check (n+1) lk x
	where 	t1 = fromJust $ M.lookup n x
		t2= fromJust $ M.lookup t1 x
		t3 = fromJust $ M.lookup t2 x
process k = do
		let x = M.fromList $ zip [1..] k
		let lk = length k
		if check 1 lk x then "Yes" else "No"

main = do
		n<-read <$> getLine ::IO Int
		k<- map read <$> words <$> getLine ::IO [Int]
		putStrLn $ process k

import Data.Array (listArray, (!))
process :: [Int] -> Bool
process xs = any (\i -> a!i /= i && a!(a!(a!i)) == i) [1..n]
    where
        n = length xs
        a = listArray (1,n) xs

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    fs <- fmap (map readInt.words) getLine
    if process fs
        then putStrLn "YES"
        else putStrLn "NO"


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. You can perform operations on it.In one operation you can replace any element of the array $$$a_i$$$ with $$$\lfloor \frac{a_i}{2} \rfloor$$$, that is, by an integer part of dividing $$$a_i$$$ by $$$2$$$ (rounding down).See if you can apply the operation some number of times (possible $$$0$$$) to make the array $$$a$$$ become a permutation of numbers from $$$1$$$ to $$$n$$$ —that is, so that it contains all numbers from $$$1$$$ to $$$n$$$, each exactly once.For example, if $$$a = [1, 8, 25, 2]$$$, $$$n = 4$$$, then the answer is yes. You could do the following:  Replace $$$8$$$ with $$$\lfloor \frac{8}{2} \rfloor = 4$$$, then $$$a = [1, 4, 25, 2]$$$.  Replace $$$25$$$ with $$$\lfloor \frac{25}{2} \rfloor = 12$$$, then $$$a = [1, 4, 12, 2]$$$.  Replace $$$12$$$ with $$$\lfloor \frac{12}{2} \rfloor = 6$$$, then $$$a = [1, 4, 6, 2]$$$.  Replace $$$6$$$ with $$$\lfloor \frac{6}{2} \rfloor = 3$$$, then $$$a = [1, 4, 3, 2]$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases. Each test case contains exactly two lines. The first one contains an integer $$$n$$$ ($$$1 \le n \le 50$$$), the second one contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each test case, output on a separate line:   YES if you can make the array $$$a$$$ become a permutation of numbers from $$$1$$$ to $$$n$$$,  NO otherwise.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

NoteThe first test case is explained in the text of the problem statement.In the second test case, it is not possible to get a permutation.

import Data.ByteString.Char8 (ByteString)
import Data.Maybe (fromJust, listToMaybe)
import Data.Set (Set)
import Control.Monad ( foldM )

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as S

main :: IO()
main = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words

parse :: [Int] -> [ByteString]
parse (n:rest) = solve n (take n rest) : parse (drop n rest)
parse []       = []

solve :: Int -> [Int] -> ByteString
solve n arr = maybe (B.pack "NO") (const $ B.pack "YES") $ foldM exec S.empty arr where
    exec mySet x = (`S.insert` mySet) <$> cook_x where
        cook_x = listToMaybe $ dropWhile bad $ takeWhile (>0) $ iterate (`div` 2) x
        bad y = y > n || S.member y mySet

import Data.ByteString.Char8 (ByteString)
import Data.Maybe (fromJust)
import Data.List (sort)
import Data.Set (Set)

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as S

main :: IO()
main = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words

parse :: [Int] -> [ByteString]
parse (n:rest) = solve n (take n rest) S.empty : parse (drop n rest)
parse []       = []

solve :: Int -> [Int] -> Set Int -> ByteString
solve n (x:xs) mySet = if new_x == 0 then (B.pack "NO") else
    solve n xs (S.insert new_x mySet)
    where
        new_x = judge good_x mySet
        good_x = sitdown x n
solve _ [] _ = B.pack "YES"

sitdown :: Int -> Int -> Int
sitdown x n = if x <= n then x else sitdown (div x 2) n

judge :: Int -> Set Int -> Int
judge x mySet = if S.member x mySet then judge (div x 2) mySet else x

import Data.ByteString.Char8 (ByteString)
import Data.Maybe (fromJust)
import Data.List (sort)
import Data.Set (Set)

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as S

main :: IO()
main = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words

parse :: [Int] -> [ByteString]
parse (n:rest) = solve n (sort . take n $ rest) S.empty : parse (drop n rest)
parse []       = []

solve :: Int -> [Int] -> Set Int -> ByteString
solve n (x:xs) mySet = if new_x == 0 then (B.pack "NO") else
    solve n xs (S.insert new_x mySet)
    where
        new_x = judge good_x mySet
        good_x = sitdown x n
solve _ [] _ = B.pack "YES"

sitdown :: Int -> Int -> Int
sitdown x n = if x <= n then x else sitdown (div x 2) n

judge :: Int -> Set Int -> Int
judge x mySet = if S.member x mySet then judge (div x 2) mySet else x

import Data.Char
import Data.List ((\\))

main :: IO()
main = do
    tStr <- getLine
    let t = read tStr :: Int
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do
    nStr <- getLine
    let n = read nStr :: Int

    aStr <- getLine
    let as = readIntList aStr

    let ans = if possible (minimize as) n then "YES" else "NO"

    putStrLn ans
    solve (t-1)

minimize :: [Int] -> [Int]
minimize = map change

change :: Int -> Int
change a
    | a > 50 = change (a `div` 2)
    | otherwise = a

possible :: [Int] -> Int -> Bool
possible [] n = True
possible as n
    | maxi < n = False
    | maxi == n = possible (as \\ [maxi]) (n-1)
    | maxi > n = possible (newEl : (as \\ [maxi])) n
    | otherwise = False
        where
            maxi = foldr max 0 as
            newEl = maxi `div` 2

readIntList :: String -> [Int]
readIntList [] = []
readIntList (h : t)
    | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)
    | otherwise = readIntList t

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

solve :: IO ()
solve = do
    ~[n] <- readInts
    as <- readInts
    let go have x = (:have) <$> x' where
            bad y = y > n || y `elem` have
            x' = listToMaybe $ dropWhile bad $ takeWhile (>0) $ iterate (`div` 2) x
    putStrLn $ maybe "NO" (const "YES") $ foldM go [] as

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

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

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

readInt :: IO Int
readInt = readLn

readIntArray :: IO [Int]
readIntArray = (map read . words) <$> getLine

main :: IO ()
main = readInt >>= \t -> replicateM_ t test

test :: IO ()
test = do
    n <- readInt
    dt <- (reverse . sort) <$> readIntArray
    putStrLn $ if can dt then "YES" else "NO"

minimize :: Int -> Int -> [Int] -> [Bool] -> Int -> Bool
minimize n pos dt used x
  | pos == n = True
  | x == 0 = False
  | x > n = minimize n pos dt used (div x 2)
  | x <= n && not (used !! x) = minimize n pos dt used (div x 2)
  | otherwise = minimize n nxt dt newUsed (dt !! nxt)
    where
      (left, right) = splitAt x used
      (remove : need) = right
      newUsed = left ++ [False] ++ need
      nxt = pos + 1

can :: [Int] -> Bool
can dt = minimize n 0 dt [True | _ <- [0..n]] (dt !! 0)
  where n = length dt

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

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

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    a <- getInts n
    let
      initArr :: UArray Int Bool
      initArr = listArray (1, n) $ replicate n False
      step :: UArray Int Bool -> Int -> UArray Int Bool
      step arr x = if  x > n || (x >= 1 && arr ! x)
        then  step arr (x `div` 2)
        else  arr // [(x, True) | x >= 1]
      ans = and $ elems $ foldl' step initArr a
    pure $ string7 $ if  ans
      then  "YES\n"
      else  "NO\n"

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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

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

import Data.Char
import Data.List ((\\))

main :: IO()
main = do
    tStr <- getLine
    let t = read tStr :: Int
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do
    nStr <- getLine
    let n = read nStr :: Int

    aStr <- getLine
    let as = readIntList aStr

    let ans = if possible (minimize as) n then "YES" else "NO"

    putStrLn ans
    solve (t-1)

minimize :: [Int] -> [Int]
minimize = map change

change :: Int -> Int
change a
    | a > 50 = change (a `div` 50)
    | otherwise = a

possible :: [Int] -> Int -> Bool
possible [] n = True
possible as n
    | maxi < n = False
    | maxi == n = possible (as \\ [maxi]) (n-1)
    | maxi > n = possible (newEl : (as \\ [maxi])) n
    | otherwise = False
        where
            maxi = foldr max 0 as
            newEl = maxi `div` 2

readIntList :: String -> [Int]
readIntList [] = []
readIntList (h : t)
    | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)
    | otherwise = readIntList t