You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries.  Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.

Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.

NoteIn the first example here are how teams are formed:  the only team of 1 coder, 1 mathematician and 1 without specialization;  all three teams consist of 1 coder and 2 mathematicians;  no teams can be formed;  no teams can be formed;  one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team;  one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input =
  let n :: Int
      (n:xs) = map read $ words input
      queries = bythree xs
      answers = map solve' queries
  in intercalate "\n" $ map show answers

bythree :: [Int] -> [(Int, Int, Int)]
bythree [] = []
bythree (a:b:c:xs) = (a, b, c):(bythree xs)

solve' :: (Int, Int, Int) -> Int
solve' (a, b, c) =
  let base = minimum (a:b:c:[])
      a' = a - base
      b' = b - base
      c' = c - base
      cleft = c == base
  in if cleft then
       base + min (div (a' + b') 3) (min a' b')
    else
       base

{-# LANGUAGE MultiWayIf #-}

import Control.Monad

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n $ do
    [c, m, x] <- map read . words <$> getLine
    print $ solve c m x

solve :: Int -> Int -> Int -> Int
solve c' m' x' = mx + oth
  where oth = if
          | c == 0 || m == 0 -> 0
          | 2 * c < m -> c
          | 2 * m < c -> m
          | otherwise -> (c + m) `div` 3
        mx = minimum [c', m', x']
        (c, m, x) = (c' - mx, m' - mx, x' - mx)

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input =
  let n :: Int
      (n:xs) = map read $ words input
      queries = bythree xs
      answers = map solve' queries
  in intercalate "\n" $ map show answers

bythree :: [Int] -> [(Int, Int, Int)]
bythree [] = []
bythree (a:b:c:xs) = (a, b, c):(bythree xs)

solve' :: (Int, Int, Int) -> Int
solve' (a, b, c) =
  let base = minimum (a:b:c:[])
      a' = a - base
      b' = b - base
      c' = c - base
      cleft = c == base
  in if cleft then
       base + (div (a' + b') 3)
    else
       base

import Control.Monad

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n $ do
    [c, m, x] <- map read . words <$> getLine
    print $ solve c m x

solve :: Int -> Int -> Int -> Int
solve c m x = h c m x 0
  where h c m x acc
          | c == 0 || m == 0 || c + m + x < 3 = acc
          | x /= 0 = h (c - 1) (m - 1) (x - 1) (acc + 1)
          | c > m = h (c - 2) (m - 1) 0 (acc + 1)
          | otherwise = h (c - 1) (m - 1) 0 (acc + 1)

import Control.Monad

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n $ do
    [c, m, x] <- map read . words <$> getLine
    print $ solve c m x

solve :: Int -> Int -> Int -> Int
solve c m x = mx + h (c - mx) (m - mx) (x - mx) 0
  where h c m x acc
          | c == 0 || m == 0 || c + m + x < 3 = acc
          | c > 2 * m = 2 * m
          | 2 * c > m = 2 * c
          | c > m = h (c - 2) (m - 1) 0 (acc + 1)
          | otherwise = h (c - 1) (m - 2) 0 (acc + 1)
        mx = maximum [c, m, x]


Harry Potter has a difficult homework. Given a rectangular table, consisting of n × m cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second — in the selected column. Harry's task is to make non-negative the sum of the numbers in each row and each column using these spells.Alone, the boy can not cope. Help the young magician!

The first line contains two integers n and m (1 ≤ n,  m ≤ 100) — the number of rows and the number of columns.  Next n lines follow, each contains m integers: j-th integer in the i-th line is ai, j (|ai, j| ≤ 100), the number in the i-th row and j-th column of the table. The rows of the table numbered from 1 to n. The columns of the table numbered from 1 to m.

In the first line print the number a — the number of required applications of the first spell. Next print a space-separated integers — the row numbers, you want to apply a spell. These row numbers must be distinct! In the second line print the number b — the number of required applications of the second spell. Next print b space-separated integers — the column numbers, you want to apply a spell. These column numbers must be distinct! If there are several solutions are allowed to print any of them.

import Array (Array, (!), (//), array, assocs, bounds, listArray)
import Data.List (minimumBy)
import Data.Function (on)

solve :: Array (Int, Int) Int -> ([Int], [Int])
solve a  =  solve' inverseRows inverseCols sumsRows sumsCols
  where
    (n, m)   =  snd $ bounds a
    sumsRows  =  array (1, n) [(i, sum [a ! (i,j) | j <- [1..m]]) | i <- [1..n]]
    sumsCols  =  array (1, m) [(j, sum [a ! (i,j) | i <- [1..n]]) | j <- [1..m]]
    inverseRows  =  array (1, n) [(i, False) | i <- [1..n]]
    inverseCols  =  array (1, m) [(j, False) | j <- [1..m]]
    solve' inverseRows inverseCols sumsRows sumsCols
      | minSumsRows >= 0 && minSumsCols >= 0
        =  ([i | i <- [1..n], inverseRows ! i], [j | j <- [1..m], inverseCols ! j])
      | minSumsRows < minSumsCols  =  solve'
            (inverseRows // [(indexMinSumsRows, not $ inverseRows ! indexMinSumsRows)])
            inverseCols
            (sumsRows // [(indexMinSumsRows, (-1) * sumsRows ! indexMinSumsRows)])
            (sumsCols // [(j, sumsCols ! j - 2 * (f indexMinSumsRows j) * a ! (indexMinSumsRows, j)) | j <- [1..m]])
      | otherwise  =  solve'
            inverseRows
            (inverseCols // [(indexMinSumsCols, not $ inverseCols ! indexMinSumsCols)])
            (sumsRows // [(i, sumsRows ! i - 2 * (f i indexMinSumsCols) * a ! (i, indexMinSumsCols)) | i <- [1..n]])
            (sumsCols // [(indexMinSumsCols, (-1) * sumsCols ! indexMinSumsCols)])
      where
        (indexMinSumsRows, minSumsRows)  =  minimumBy (on compare snd) (assocs sumsRows)
        (indexMinSumsCols, minSumsCols)  =  minimumBy (on compare snd) (assocs sumsCols)
        f i j  =  if (inverseRows ! i) == (inverseCols ! j) then 1 else (-1)

main :: IO ()
main  =  do
    [n, m]  <-  fmap (map read . words) getLine
    xs      <-  fmap (map read . words) getContents
    let (as, bs)  =  solve (listArray ((1,1), (n,m)) xs)
    putStr . show . length $ as
    putStrLn . concatMap (\n -> " " ++ show n) $ as
    putStr . show . length $ bs
    putStrLn . concatMap (\n -> " " ++ show n) $ bs


Recall that a permutation of length $$$n$$$ is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once.For a fixed positive integer $$$d$$$, let's define the cost of the permutation $$$p$$$ of length $$$n$$$ as the number of indices $$$i$$$ $$$(1 \le i < n)$$$ such that $$$p_i \cdot d = p_{i + 1}$$$.For example, if $$$d = 3$$$ and $$$p = [5, 2, 6, 7, 1, 3, 4]$$$, then the cost of such a permutation is $$$2$$$, because $$$p_2 \cdot 3 = p_3$$$ and $$$p_5 \cdot 3 = p_6$$$.Your task is the following one: for a given value $$$n$$$, find the permutation of length $$$n$$$ and the value $$$d$$$ with maximum possible cost (over all ways to choose the permutation and $$$d$$$). If there are multiple answers, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The single line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the value $$$d$$$ in the first line, and $$$n$$$ integers in the second line — the permutation itself. If there are multiple answers, then print any of them.

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L
import Data.Maybe
import Data.Set              qualified as Set

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n] <- ri
        return n
    mapM_ (putStr . showAns . solve) tcs

showAns xs = unlines ["2", unwords . map show $ xs]

solve n = concat . reverse . snd . fst . fromJust . L.find (Set.null . snd) . iterate (step n) $ ini
  where
    ini = ((Set.empty, []), Set.fromList nums)
    nums = [1..n] :: [Int]

step n ((yset0,ys0), xset0) = ((yset0 `Set.union` eset,
                                es : ys0),
                               xset0 Set.\\ eset)
  where
    h = Set.elemAt 0 xset0
    es = filter (`Set.notMember`yset0) . takeWhile (<=n) . iterate (*2) $ h
    eset = Set.fromList es

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L
import Data.Maybe
import Data.IntSet           qualified as Set

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n] <- ri
        return n
    mapM_ (putStr . showAns . solve) tcs

showAns xs = unlines ["2", unwords . map show $ xs]

solve n = concat . reverse . snd . fst . fromJust . L.find (Set.null . snd) . iterate (step n) $ ini
  where
    ini = ((Set.empty, []), Set.fromList nums)
    nums = [1..n] :: [Int]

step n ((yset0,ys0), xset0) = ((yset1, diff : ys0),
                               xset1)
  where
    h = Set.findMin xset0
    ((yset1, diff), xset1)
        | (2*h > n)  = ((Set.empty,              Set.toList xset0), Set.empty        )
        | otherwise  = ((yset0 `Set.union` eset, es              ), xset0 Set.\\ eset)
    eset = Set.fromDistinctAscList es
    es = filter (`Set.notMember`yset0) . takeWhile (<=n) . iterate (*2) $ h

import Data.IntSet (IntSet, empty, member, fromList, union)

calcH :: Int -> Int -> [Int]
calcH n a = if a > n
  then []
  else (a: calcH n (2 * a))

calcHH :: Int -> IntSet -> Int -> [Int]
calcHH n a x = if x > n
  then []
  else if x `member` a
    then calcHH n a (x + 1)
    else let a1 = calcH n x in a1 ++ calcHH n (a `union` ( fromList a1)) (x + 1)

calc :: Int -> [Int]
calc n = calcHH n empty 1

pr :: [Int] -> IO ()
pr a = putStrLn $ concat $ map (\x -> show x ++ " ") a

for :: Int -> IO ()
for 0 = pure ()
for i = do
  n <- readLn :: IO Int
  print 2
  pr $ calc n
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n

import Control.Monad

solve :: Int -> (Int, [Int])
solve n = (2, concat [takeWhile (<= n) $ iterate (* 2) m | m <- [1, 3 .. n]])

testCase :: IO ()
testCase = do
    n <- readLn
    let (d, nums) = solve n
    print d
    putStrLn . unwords $ map show nums

main :: IO ()
main = readLn >>= (`replicateM_` testCase)

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- {-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad as M
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S
import qualified Control.Monad.Trans.Class as T

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Ix as Ix
import qualified Data.Ratio as R

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
    hFlush
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)
import qualified Data.Array.IO.Safe as UOA

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace
--
-- tracing t x = trace (t ++ " = " ++ show x) x
-- debugging x t = tracing t x
--
-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: Int -> (Int, [Int])
solve n = (d, ps)
    where
        d = 2
        ps = solve' $ IS.fromList [1 .. n]

        solve' :: IS.IntSet -> [Int]
        solve' is = if (IS.size is == 0)
                then []
                else ts ++ solve' leastIs
            where
                i = IS.findMin is
                ts = L.takeWhile (<= n) $ L.iterate (* d) i
                leastIs = L.foldl' (flip IS.delete) is ts

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        let (d, ps) = solve n
        printf "%d\n" d
        forM_ ps $ printf "%d "
        putStrLn ""

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow         hiding (loop)
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.IntSet           qualified as Set
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n] <- ri
        return n
    mapM_ (putStr.showAns.solve) tcs

showAns xs = unlines ["2", unwords . map show $ xs]

solve n = for2 ++ remdr
  where
    for2 = concat . takeWhile (not.null) . ([1]:) . map (takeWhile (<=n) . iterate (*2)) $ primes
    remdr = Set.toList . (Set.\\ for2set) . Set.fromList $ [1..n]
    for2set = Set.fromList for2

----------------------------
primes :: [Int]
primes = ppp  where  ppp = 2 : 3 : minus [5,7..] (unionAll [[p*p, p*p+2*p..] | p <- tail ppp])
minus :: Ord a => [a] -> [a] -> [a]
minus = minusBy compare
minusBy :: (a -> b -> Ordering) -> [a] -> [b] -> [a]
minusBy cmp = loop
  where
     loop [] _ys = []
     loop xs [] = xs
     loop (x:xs) (y:ys)
       = case cmp x y of
          LT -> x : loop xs (y:ys)
          EQ ->     loop xs ys
          GT ->     loop (x:xs) ys
unionAll :: Ord a => [[a]] -> [a]
unionAll = unionAllBy compare
unionAllBy :: (a -> a -> Ordering) -> [[a]] -> [a]
unionAllBy cmp = serve . foldt union' (Crowd []) . vips
  where
    msg = "Data.List.Ordered.unionAllBy:  the heads of the lists are not sorted"

    union' (VIP x xs) ys
       = VIP x $ case ys of
                  Crowd _ -> union' xs ys
                  VIP y yt -> case cmp x y of
                               LT -> union' xs ys
                               EQ -> union' xs yt
                               GT -> error msg
    union' (Crowd []) ys = ys
    union' (Crowd xs) (Crowd ys) = Crowd (unionBy cmp xs ys)
    union' xs@(Crowd (x:xt)) ys@(VIP y yt)
       = case cmp x y of
           LT -> VIP x (union' (Crowd xt) ys)
           EQ -> VIP x (union' (Crowd xt) yt)
           GT -> VIP y (union' xs yt)
data People a = VIP a (People a) | Crowd [a]
serve (VIP x xs) = x:serve xs
serve (Crowd xs) = xs
foldt :: (a -> a -> a) -> a -> [a] -> a
foldt plus zero = loop
  where
    loop []     = zero
    loop (x:xs) = x `plus` loop (pairs xs)

    pairs (x:y:zs) = plus x y : pairs zs
    pairs zs       = zs
vips xss = [ VIP x (Crowd xs) | (x:xs) <- xss ]
unionBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
unionBy cmp = loop
  where
     loop [] ys = ys
     loop xs [] = xs
     loop (x:xs) (y:ys)
       = case cmp x y of
          LT -> x : loop xs (y:ys)
          EQ -> x : loop xs ys
          GT -> y : loop (x:xs) ys
----------------------------

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n] <- ri
        return n
    mapM_ (putStr . showAns 2 . solve 2) tcs

showAns d xs = unlines [show (d::Int), unwords . map show $ xs]

solve d n = ds ++ os
  where
    (ds, os) = L.partition isD inds
    isD x = (x == 1 || x`mod`d == 0)
    inds = [1..n] :: [Int]

calcH :: Int -> Int -> [Int]
calcH n a = if a > n
  then []
  else (a: calcH n (2 * a))

calcHH :: Int -> [Int] -> Int -> [Int]
calcHH n a x = if x > n
  then []
  else if x `elem` a
    then calcHH n a (x + 1)
    else (x: calcHH n a (x + 1))

calc :: Int -> [Int]
calc n = let a = calcH n 1 in a ++ calcHH n a 1

pr :: [Int] -> IO ()
pr a = putStrLn $ concat $ map (\x -> show x ++ " ") a

for :: Int -> IO ()
for 0 = pure ()
for i = do
  n <- readLn :: IO Int
  print 2
  pr $ calc n
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n


Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). Makes has chosen n problems to solve on Decoforces with difficulties a1, a2, ..., an. He can solve these problems in arbitrary order. Though he can solve problem i with difficulty ai only if he had already solved some problem with difficulty  (no matter on what online judge was it).Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty k.With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer y there exist some problem with difficulty y on at least one judge besides Decoforces.Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.

The first line contains two integer numbers n, k (1 ≤ n ≤ 103, 1 ≤ k ≤ 109). The second line contains n space-separated integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print minimum number of problems Makes should solve on other judges in order to solve all chosen problems on Decoforces.

NoteIn the first example Makes at first solves problems 1 and 2. Then in order to solve the problem with difficulty 9, he should solve problem with difficulty no less than 5. The only available are difficulties 5 and 6 on some other judge. Solving any of these will give Makes opportunity to solve problem 3.In the second example he can solve every problem right from the start.

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

main = do
  [n, k] <- fmap readInts B.getLine
  xs <- fmap readInts B.getLine
  print $ solve k xs

solve k = snd . foldl (\(!t, !c) x -> if x > 2 * t then (x, c + ceiling (logBase 2 $ fromIntegral x / 2 / fromIntegral t)) else (max x t, c)) (k, 0) . sort

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

import Data.Traversable (mapAccumL)
import Control.Arrow (second)
import Data.Functor ((<$>))
import Data.List (sort)

fun :: Int -> Int -> (Int, Int)
fun a x | 2 * a >= x = (max a x, 0)
        | otherwise  = second (+1) $ fun (2 * a) x

main = do
  [_, k] <- map read <$> words <$> getLine
  xs <- sort <$> map read <$> words <$> getLine
  putStrLn $ show $ sum $ snd $ mapAccumL fun k xs

import Data.List
import Control.Applicative

type MaxSolvedDifficulty = Int
type DecoforcesProblems = [Int]
type Accum = Int

f :: MaxSolvedDifficulty -> DecoforcesProblems -> Accum -> Accum
f k (x:xs) acc
  | x <= k*2     = f (max x k) xs acc
  | otherwise    = f (k*2) (x:xs) (acc + 1)

f _ [] acc = acc

main = interact (show . (\[[_, k], a] -> f k (sort a) 0) . (map (map (read :: String -> Int) . words) . lines))

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

main = do
  [n, k] <- fmap readInts B.getLine
  xs <- fmap readInts B.getLine
  print $ solve k xs

solve k = snd . foldl (\(!t, !c) x -> if x > 2 * t then (x, c + 1) else (x, c)) (k, 0) . sort

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

import Data.Traversable (mapAccumL)
import Control.Arrow (second)
import Data.Functor ((<$>))

fun :: Int -> Int -> (Int, Int)
fun a x | 2 * a >= x = (a, 0)
        | otherwise  = second (+1) $ fun (2 * a) x

main = do
  [_, k] <- map read <$> words <$> getLine
  xs <- map read <$> words <$> getLine
  putStrLn $ show $ sum $ snd $ mapAccumL fun k xs

import Data.Traversable (mapAccumL)
import Control.Arrow (second)
import Data.Functor ((<$>))
import Data.List (sort)

fun :: Int -> Int -> (Int, Int)
fun a x | 2 * a >= x = (a, 0)
        | otherwise  = second (+1) $ fun (2 * a) x

main = do
  [_, k] <- map read <$> words <$> getLine
  xs <- sort <$> map read <$> words <$> getLine
  putStrLn $ show $ sum $ snd $ mapAccumL fun k xs

import Data.Traversable (mapAccumL)
import Control.Arrow (second)
import Data.Functor ((<$>))
import Data.List (sort)

fun :: Int -> Int -> (Int, Int)
fun a x | 2 * a >= x = (a, 0)
        | otherwise  = second (+1) $ fun (2 * a) x

main = do
  [_, k] <- map read <$> words <$> getLine
  xs <- map read <$> words <$> getLine
  putStrLn $ show $ sum $ snd $ mapAccumL fun k xs

import Data.List
import Control.Applicative

type MaxSolvedDifficulty = Int
type DecoforcesProblems = [Int]
type Accum = Int

f :: MaxSolvedDifficulty -> DecoforcesProblems -> Accum -> Accum
f k (x:xs) acc
  | x <= k*2     = f (max x k) xs acc
  | otherwise    = f (k*2) (x:xs) (acc + 1)

f _ [] acc = acc

main = interact (show . (\[[_, k], a] -> f k a 0) . (map (map (read :: String -> Int) . words) . lines))


Let's call left cyclic shift of some string $$$t_1 t_2 t_3 \dots t_{n - 1} t_n$$$ as string $$$t_2 t_3 \dots t_{n - 1} t_n t_1$$$.Analogically, let's call right cyclic shift of string $$$t$$$ as string $$$t_n t_1 t_2 t_3 \dots t_{n - 1}$$$.Let's say string $$$t$$$ is good if its left cyclic shift is equal to its right cyclic shift.You are given string $$$s$$$ which consists of digits 0–9.What is the minimum number of characters you need to erase from $$$s$$$ to make it good?

The first line contains single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contains test cases — one per line. The first and only line of each test case contains string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$). Each character $$$s_i$$$ is digit 0–9. It's guaranteed that the total length of strings doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print the minimum number of characters you need to erase from $$$s$$$ to make it good.

NoteIn the first test case, you can erase any $$$3$$$ characters, for example, the $$$1$$$-st, the $$$3$$$-rd, and the $$$4$$$-th. You'll get string 51 and it is good.In the second test case, we can erase all characters except 0: the remaining string is 0000 and it's good.In the third test case, the given string $$$s$$$ is already good.

{- 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
  s <- getLine
  print $
    length s
      - maximum
        ( [length $ filter (== c) s | c <- ['0' .. '9']]
            ++ [ (* 2)
                   $ flip div 2
                   $ length
                   $ map head
                   $ group
                   $ filter
                     (`elem` [c, d])
                     s
                 | c <- ['0' .. '9'],
                   d <- [succ c .. '9']
               ]
        ) -- ick haskell has ugly formatting

import Data.Bits
import Data.List

parse :: String -> [String]
parse = tail . lines

val1 :: Eq t => [t] -> t -> Int
val1 cs x = length $ filter (== x) cs

val :: Eq t => [t] -> (t, t) -> Int
val cs (x, y)
  | x == y     = val1 cs x
  | otherwise  = (.&. complement 1) . length . group $
      filter (`elem` [x, y]) cs

solve :: String -> Int
solve str = length str - maximum [val str (x, y)
  | x <- ['0' .. '9'], y <- [x .. '9']]

main :: IO ()
main = interact (unlines . map (show . solve) . parse)


This is an interactive problem.Note: the XOR-sum of an array $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) is defined as $$$a_1 \oplus a_2 \oplus \ldots \oplus a_n$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.Little Dormi received an array of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.The XOR machine is currently configured with a query size of $$$k$$$ (which you cannot change), and allows you to perform the following type of query: by giving the machine $$$k$$$ distinct indices $$$x_1, x_2, \ldots, x_k$$$, it will output $$$a_{x_1} \oplus a_{x_2} \oplus \ldots \oplus a_{x_k}$$$.As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array $$$a_1, a_2, \ldots, a_n$$$ by querying the XOR machine.Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let $$$d$$$ be the minimum number of queries needed to find the XOR-sum of any array of length $$$n$$$ with a query size of $$$k$$$. Your program will be accepted if you find the correct XOR-sum in at most $$$d$$$ queries.Lastly, you also noticed that with certain configurations of the machine $$$k$$$ and values of $$$n$$$, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.The array $$$a_1, a_2, \ldots, a_n$$$ is fixed before you start querying the XOR machine and does not change with the queries.

The only line of input contains the integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le k \le n$$$), the length of the lost array and the configured query size of the XOR machine. Elements of the original array satisfy $$$1 \le a_i \le 10^9$$$. It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most $$$500$$$ queries. That is, $$$d \le 500$$$. After taking $$$n$$$ and $$$k$$$, begin interaction.

If it is impossible to recover the XOR-sum of the array, output $$$-1$$$ immediately after taking $$$n$$$ and $$$k$$$. Do not begin interaction. Otherwise, when your program finds the XOR-sum of the lost array $$$a_1, a_2, \ldots, a_n$$$, report the answer in the following format: "! x", where $$$x$$$ is the XOR sum of the array $$$a_1, a_2, \ldots, a_n$$$, and terminate your program normally immediately after flushing the output stream.  Note that answering does not count as a query.

NoteIn the first example interaction, the array $$$a_1, a_2, \ldots, a_n$$$ is $$$2, 1, 7, 5, 6$$$ and its XOR-sum is $$$7$$$. The first query made asks for indices $$$1,2,3$$$, so the response is $$$a_1 \oplus a_2 \oplus a_3 = 2 \oplus 1 \oplus 7 = 4$$$.The second query made asks for indices $$$2,3,5$$$, so the response is $$$a_2 \oplus a_3 \oplus a_5 = 1 \oplus 7 \oplus 6 = 0$$$.The third query made asks for indices $$$4,1,5$$$, so the response is $$$a_4 \oplus a_1 \oplus a_5 = 5 \oplus 2 \oplus 6 = 1$$$. Note that the indices may be output in any order.Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs $$$-1$$$ and exits.

{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.IO
import Data.Array.Unboxed
import Data.Bits
import Data.Bool
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import System.IO
import System.IO.Unsafe

(><) a b = a Seq.>< b

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

parseInt = fst . fromJust . BS.readInt
parseInteger = fst . fromJust . BS.readInteger

type Graph = Array Int [Int]

buildG :: (Int, Int) -> [(Int, Int)] -> Graph
buildG = accumArray (flip (:)) []

genEdges :: Int -> Int -> Int -> [(Int, Int)]
genEdges _ _ (-1) = []
genEdges n k i = [(i,i-t+(k-t)) | t <- [0..(i `min` k)], k-t <= n-i] ++ genEdges n k (i-1)

main = do
    [n,k] <- map parseInt . BS.words <$> BS.getLine
    f <- newArray (0,n) (-1) :: IO (IOArray Int Int)
    let
        g = buildG (0,n) $ genEdges n k (n-1)
        bfs Seq.Empty = return ()
        bfs q = do
            let x = Seq.index q 0
            asd <- forM (g ! x) $ \y -> do
                p <- readArray f y
                if p < 0 then do
                    writeArray f y x
                    return $ Just y
                else
                    return Nothing
            let qwe = catMaybes asd
            bfs $ Seq.drop 1 q >< Seq.fromList qwe

    bfs $ Seq.singleton 0
    t <- readArray f n
    if t < 0 then do
        putStrLn "-1"
        hFlush stdout
    else do
        let
            genPath 0 = return []
            genPath x = do
                p <- readArray f x
                r <- genPath p
                return $ x : r
            iter c0 c1 [] = return 0
            iter c0 c1 (y:ys) = do
                let x = length c1
                let t = (x+k-y) `div` 2
                --putStrLn $ " " ++ show x ++ show y ++ show t
                let (c10,c11) = splitAt t c1
                let (c01,c00) = splitAt (k-t) c0
                putStrLn $ "? " ++ unwords (map show (c10 ++ c01))
                hFlush stdout
                val <- parseInt <$> BS.getLine
                r <- iter (c10++c00) (c11++c01) ys
                return $ r `xor` val

        p <- reverse <$> genPath n
        --print p
        r <- iter [1..n] [] p
        putStrLn $ "! " ++ show r
        hFlush stdout


Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought $$$n_r$$$ red gems, $$$n_g$$$ green gems and $$$n_b$$$ blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are $$$x$$$, $$$y$$$ and $$$z$$$, Xenia wants to find the minimum value of $$$(x-y)^2+(y-z)^2+(z-x)^2$$$. As her dear friend, can you help her?

The first line contains a single integer $$$t$$$ ($$$1\le t \le 100$$$)  — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n_r,n_g,n_b$$$ ($$$1\le n_r,n_g,n_b\le 10^5$$$)  — the number of red gems, green gems and blue gems respectively. The second line of each test case contains $$$n_r$$$ integers $$$r_1,r_2,\ldots,r_{n_r}$$$ ($$$1\le r_i \le 10^9$$$)  — $$$r_i$$$ is the weight of the $$$i$$$-th red gem. The third line of each test case contains $$$n_g$$$ integers $$$g_1,g_2,\ldots,g_{n_g}$$$ ($$$1\le g_i \le 10^9$$$)  — $$$g_i$$$ is the weight of the $$$i$$$-th green gem. The fourth line of each test case contains $$$n_b$$$ integers $$$b_1,b_2,\ldots,b_{n_b}$$$ ($$$1\le b_i \le 10^9$$$)  — $$$b_i$$$ is the weight of the $$$i$$$-th blue gem. It is guaranteed that $$$\sum n_r \le 10^5$$$, $$$\sum n_g \le 10^5$$$, $$$\sum n_b \le 10^5$$$ (the sum for all test cases).

For each test case, print a line contains one integer  — the minimum value which Xenia wants to find.

NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight $$$7$$$, the green gem with weight $$$6$$$, and the blue gem with weight $$$4$$$, she will achieve the most balanced selection with $$$(x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14$$$.

import qualified Data.Array as Ar
import Data.Array (Array)
import qualified Data.List as L
import qualified Data.Maybe as Mb

type Arr = Array Int

search :: Arr Integer -> Integer -> (Maybe Integer, Maybe Integer)
search arr v = search' 0 (length arr - 1)
    where
        search' start end
            | v == startVal || v == endVal  = (Just v, Just v)
            | v > endVal  = (Just endVal, Nothing)
            | v < startVal= (Nothing, Just startVal)
            | start + 1 == end   = (Just startVal, Just endVal)
            | v < midVal    = search' start mid
            | v >= midVal   = search' mid end
            where
                endVal = arr Ar.! end
                startVal = arr Ar.! start
                mid = (start + end) `div` 2
                midVal = arr Ar.! mid

justGreater :: Arr Integer -> Integer -> Maybe Integer
justGreater arr v = snd $ search arr v

justSmaller :: Arr Integer -> Integer -> Maybe Integer
justSmaller arr v = fst $ search arr v

makeArr :: [Integer] -> Arr Integer
makeArr l = Ar.listArray (0, length l - 1) l

value :: Integer -> Integer -> Integer -> Integer
value x y z = (x-y)*(x-y) + (y-z)*(y-z) + (z-x)*(z-x)

minimumTry :: [Integer] -> Maybe Integer
minimumTry [] = Nothing
minimumTry l = Just $ minimum l

findMinValue :: Arr Integer -> Arr Integer -> Arr Integer -> Maybe Integer
findMinValue xs ys zs =
    Ar.elems ys
        |> Mb.mapMaybe maybeMin
        |> minimumTry
    where
        maybeMin y =
            case (justSmaller xs y, justGreater zs y) of
                (Just x, Just z) -> Just $ value x y z
                _ -> Nothing

parse :: String -> [Integer]
parse = map read . words

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- getLine
    rs <- fmap (makeArr . L.sort . parse) getLine
    gs <- fmap (makeArr . L.sort . parse) getLine
    bs <- fmap (makeArr . L.sort . parse) getLine
    print (minimum . Mb.catMaybes $
        [ findMinValue rs gs bs
        , findMinValue rs bs gs
        , findMinValue gs rs bs
        , findMinValue gs bs rs
        , findMinValue bs rs gs
        , findMinValue bs gs rs
        ])
    testCases (t-1)

main :: IO ()
main = do
    t <- fmap read getLine
    testCases t

rs = makeArr . L.sort . parse $ "7 8"
gs = makeArr . L.sort . parse $ "6 3"
bs = makeArr . L.sort . parse $ "3 1 4"

test :: String
test = show $ findMinValue rs gs bs

(|>) = flip ($)


Recently, Masha was presented with a chessboard with a height of $$$n$$$ and a width of $$$m$$$.The rows on the chessboard are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. Therefore, each cell can be specified with the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number, and $$$y$$$ is the row number (do not mix up).Let us call a rectangle with coordinates $$$(a,b,c,d)$$$ a rectangle lower left point of which has coordinates $$$(a,b)$$$, and the upper right one — $$$(c,d)$$$.The chessboard is painted black and white as follows:   An example of a chessboard. Masha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat — they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled white paint on the rectangle $$$(x_1,y_1,x_2,y_2)$$$. Then after him Denis spilled black paint on the rectangle $$$(x_3,y_3,x_4,y_4)$$$.To spill paint of color $$$color$$$ onto a certain rectangle means that all the cells that belong to the given rectangle become $$$color$$$. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black).Masha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers!

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each of them is described in the following format: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^9$$$) — the size of the board. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1 \le x_2 \le m, 1 \le y_1 \le y_2 \le n$$$) — the coordinates of the rectangle, the white paint was spilled on. The third line contains four integers $$$x_3$$$, $$$y_3$$$, $$$x_4$$$, $$$y_4$$$ ($$$1 \le x_3 \le x_4 \le m, 1 \le y_3 \le y_4 \le n$$$) — the coordinates of the rectangle, the black paint was spilled on.

Output $$$t$$$ lines, each of which contains two numbers — the number of white and black cells after spilling paint, respectively.

NoteExplanation for examples:The first picture of each illustration shows how the field looked before the dyes were spilled. The second picture of each illustration shows how the field looked after Maxim spoiled white dye (the rectangle on which the dye was spilled is highlighted with red). The third picture in each illustration shows how the field looked after Denis spoiled black dye (the rectangle on which the dye was spilled is highlighted with red).In the first test, the paint on the field changed as follows:  In the second test, the paint on the field changed as follows:  In the third test, the paint on the field changed as follows:  In the fourth test, the paint on the field changed as follows:  In the fifth test, the paint on the field changed as follows:

module Main where
import Data.Int
import Control.Applicative
import Data.Maybe
default (Int64)
main = interact exec
exec = unlines . map ((\(a, b) -> unwords $ map show [a, b]) . solve) . every 10 . tail . map read . words
solve [n, m, x1, y1, x2, y2, x3, y3, x4, y4] | b <- onblk m n - nblk (x1, y1) (x2, y2) + nwhi (x3, y3) (x4, y4) + maybe 0 (uncurry nblk) (insec ((x1, y1), (x2, y2)) ((x3, y3), (x4, y4))) = (m * n - b, b)
every _ [] = []
every n xs | ~(ys, zs) <- splitAt n xs = ys:every n zs
onblk x y = x * y `quot` 2
nblk (x1, y1) (x2, y2) = onblk x2 y2 - onblk (x1 - 1) y2 - onblk x2 (y1 - 1) + onblk (x1 - 1) (y1 - 1)
nwhi a b = area a b - nblk a b
area (x1, y1) (x2, y2) = (x2 - x1 + 1) * (y2 - y1 + 1)
insec ((x1, y1), (x2, y2)) ((x3, y3), (x4, y4))
  | r <- ((max x1 x3, max y1 y3), (min x2 x4, min y2 y4)), ((x5, y5), (x6, y6)) <- r, x5 <= x6 && y5 <= y6 = Just r
  | otherwise = Nothing


Diamond Miner is a game that is similar to Gold Miner, but there are $$$n$$$ miners instead of $$$1$$$ in this game.The mining area can be described as a plane. The $$$n$$$ miners can be regarded as $$$n$$$ points on the y-axis. There are $$$n$$$ diamond mines in the mining area. We can regard them as $$$n$$$ points on the x-axis. For some reason, no miners or diamond mines can be at the origin (point $$$(0, 0)$$$). Every miner should mine exactly one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point $$$(a,b)$$$ uses his hook to mine a diamond mine at the point $$$(c,d)$$$, he will spend $$$\sqrt{(a-c)^2+(b-d)^2}$$$ energy to mine it (the distance between these points). The miners can't move or help each other.The object of this game is to minimize the sum of the energy that miners spend. Can you find this minimum?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of miners and mines. Each of the next $$$2n$$$ lines contains two space-separated integers $$$x$$$ ($$$-10^8 \le x \le 10^8$$$) and $$$y$$$ ($$$-10^8 \le y \le 10^8$$$), which represent the point $$$(x,y)$$$ to describe a miner's or a diamond mine's position. Either $$$x = 0$$$, meaning there is a miner at the point $$$(0, y)$$$, or $$$y = 0$$$, meaning there is a diamond mine at the point $$$(x, 0)$$$. There can be multiple miners or diamond mines at the same point. It is guaranteed that no point is at the origin. It is guaranteed that the number of points on the x-axis is equal to $$$n$$$ and the number of points on the y-axis is equal to $$$n$$$. It's guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, print a single real number — the minimal sum of energy that should be spent. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-9}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-9}$$$.

NoteIn the first test case, the miners are at $$$(0,1)$$$ and $$$(0,-1)$$$, while the diamond mines are at $$$(1,0)$$$ and $$$(-2,0)$$$. If you arrange the miners to get the diamond mines in the way, shown in the picture, you can get the sum of the energy $$$\sqrt2 + \sqrt5$$$.

import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.Int
import Data.List

solve :: [[Int]] -> Double
solve =
  sum
    . map (sqrt . fromIntegral)
    . foldl1 (zipWith (+))
    . map
      ( map ((\x -> x * x) . (fromIntegral :: Int -> Int64))
          . sort
          . map abs
      )

solve' :: [[Int]] -> Double
solve' coords =
  let (miners', mines') = partition ((== 0) . head) coords
   in solve [map (!! 0) mines', map (!! 1) miners']

main :: IO ()
main = do
  [t] <- readL
  replicateM_ t $ do
    [n] <- readL
    coords <- replicateM (2 * n) readL
    print $ solve' coords

readI :: B.ByteString -> Int
readI s = case B.readInt s of Just (n, _) -> n

readL :: IO [Int]
readL = fmap (map readI . B.words) B.getLine


There are $$$n$$$ piranhas with sizes $$$a_1, a_2, \ldots, a_n$$$ in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them.Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely:   The piranha $$$i$$$ can eat the piranha $$$i-1$$$ if the piranha $$$i-1$$$ exists and $$$a_{i - 1} < a_i$$$.  The piranha $$$i$$$ can eat the piranha $$$i+1$$$ if the piranha $$$i+1$$$ exists and $$$a_{i + 1} < a_i$$$. When the piranha $$$i$$$ eats some piranha, its size increases by one ($$$a_i$$$ becomes $$$a_i + 1$$$).Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas.Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them.For example, if $$$a = [5, 3, 4, 4, 5]$$$, then the third piranha can be dominant. Consider the sequence of its moves:   The piranha eats the second piranha and $$$a$$$ becomes $$$[5, \underline{5}, 4, 5]$$$ (the underlined piranha is our candidate).  The piranha eats the third piranha and $$$a$$$ becomes $$$[5, \underline{6}, 5]$$$.  The piranha eats the first piranha and $$$a$$$ becomes $$$[\underline{7}, 5]$$$.  The piranha eats the second piranha and $$$a$$$ becomes $$$[\underline{8}]$$$. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of piranhas in the aquarium. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the size of the $$$i$$$-th piranha. It is guaranteed that the sum of $$$n$$$ does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).

For each test case, print the answer: -1 if there are no dominant piranhas in the aquarium or index of any dominant piranha otherwise. If there are several answers, you can print any.

NoteThe first test case of the example is described in the problem statement.In the second test case of the example, there are no dominant piranhas in the aquarium.In the third test case of the example, the fourth piranha can firstly eat the piranha to the left and the aquarium becomes $$$[4, 4, 5, 4]$$$, then it can eat any other piranha in the aquarium.

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
import safe Data.Tuple (swap)

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

process :: [[Int]] -> [Int]
process [] = []
process (_ : xs : xss) = solve xs : process xss

solve :: [Int] -> Int
solve xs
  | all (== head xs) xs = -1
  | otherwise = snd . maximum . filter (ok . fst) . zipWith (curry swap) [1 ..] $ zip3 xs (tail xs ++ [inf]) (inf : xs)
  where
    ok (x, y, z) = x > min y z
    inf = 10 ^ 9 + 1

module Main where

import Control.Monad (replicateM_)

import qualified Control.Monad.Reader as R
import qualified Control.Monad.State.Strict as ST

main :: IO ()
main = do
    numCases <- (read :: String -> Int) <$> getLine
    replicateM_ numCases solveOne

newtype Size  = Size Int
newtype Index = Index Int

solveOne :: IO ()
solveOne = do
    getLine  -- We get some unnecessary input from the test cases.
    piranhas@(p : ps) <- map (read :: String -> Int) . words <$> getLine

    let maxSize = maximum piranhas
    if p == maxSize && p > head ps
        then print 1
        else print $ R.runReader (go startIndex piranhas) (Size maxSize)
  where
    -- 2 because Codeforce counts from 1, and we skip the first element.
    startIndex :: Index
    startIndex = Index 2

go :: Index -> [Int] -> R.Reader Size Int
go _ []     = return (-1)
go _ [_]    = return (-1)
go (Index i) [x, y] = do
    Size maxSize <- R.ask
    if y == maxSize && y > x
        then return i
        else return (-1)
go (Index i) (x : y : z : xs) = do
    Size maxSize <- R.ask
    if y == maxSize && (y > x || y > z)
        then return i
        else go (Index $ i + 1) $ y : z : xs

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    _ <- getInts
    as <- getInts
    let xs = zip3 as (tail as) [(1::Int)..]
        m = maximum as
        l1 = filter (\(a, b, _) -> a == m && a > b) xs
        l2 = filter (\(a, b, _) -> b == m && a < b) xs
        notNull = not . null
    putStrLn $ show $ if notNull l1
                        then let (_, _, r) = head l1 in r
                        else if notNull l2
                               then let (_, _, r) = head l2 in r + 1
                               else -1

import Control.Monad

readInt :: IO Int
readInt =  read <$> getLine

readInts :: IO [Int]
readInts = map read . words <$> getLine

main :: IO ()
main = do
    t <- readInt
    replicateM_ t $ do
        n <- readInt
        a <- readInts
        print $ solve a

solve :: [Int] -> Int
solve a = if null $ filter (/= m) a then -1 else index
        where m = maximum a
              index
                  | head a == m = length $ takeWhile (== m) a
                  | otherwise = succ $ length $ takeWhile (/= m) a

module Main where

import Control.Monad (replicateM_)

import qualified Control.Monad.Reader as R
import qualified Control.Monad.State.Strict as ST

main :: IO ()
main = do
    numCases <- (read :: String -> Int) <$> getLine
    replicateM_ numCases solveOne

newtype Size  = Size Int
newtype Index = Index Int

solveOne :: IO ()
solveOne = do
    getLine  -- We get some unnecessary input from the test cases.
    piranhas@(p : ps) <- map (read :: String -> Int) . words <$> getLine

    let maxSize = maximum piranhas
    if p > head ps
        then print 1
        else print $ R.runReader (go startIndex piranhas) (Size maxSize)
  where
    -- 2 because Codeforce counts from 1, and we skip the first element.
    startIndex :: Index
    startIndex = Index 2

go :: Index -> [Int] -> R.Reader Size Int
go _ []     = return (-1)
go _ [_]    = return (-1)
go (Index i) [x, y] = do
    Size maxSize <- R.ask
    if y == maxSize && y > x
        then return i
        else return (-1)
go (Index i) (x : y : z : xs) = do
    Size maxSize <- R.ask
    if y == maxSize && (y > x || y > z)
        then return i
        else go (Index $ i + 1) $ y : z : xs


As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.

The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.

Print a single number — the maximum size of a clique in a divisibility graph for set A.

NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.

import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Array.Unboxed (UArray, accumArray, (!), elems)

import Control.Monad (mapM, forM, when, forM_)
import Control.Monad.ST.Strict (ST)
import Data.Array.Unboxed (UArray)
import Data.Array.ST (STUArray, newArray, readArray, writeArray, runSTUArray)

solve :: [Int] -> Int
solve a = maximum . elems $ dag
    where
    size = maximum a :: Int
    arr = accumArray (+) 0 (1, size) . zip a . repeat $ 1 :: UArray Int Int

    adj :: Int -> [Int]
    adj i = takeWhile (< size + 1) [2*i, 3*i..]

    dag :: UArray Int Int
    dag = runSTUArray $ do
        out <- newArray (1, size) 0 :: ST s (STUArray s Int Int)
        forM_ [size, size - 1..1] $ \i -> do
            let inc = arr ! i
            when (inc /= 0) $ do
                jump <- mapM (readArray out) (adj i)
                case jump of
                    []        -> writeArray out i inc
                    otherwise -> writeArray out i (inc + maximum jump)

        return out

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = B.getLine >> parse <$> B.getLine >>= print . solve


Mirror Box is a name of a popular game in the Iranian National Amusement Park (INAP). There is a wooden box, 105 cm long and 100 cm high in this game. Some parts of the box's ceiling and floor are covered by mirrors. There are two negligibly small holes in the opposite sides of the box at heights hl and hr centimeters above the floor. The picture below shows what the box looks like.  In the game, you will be given a laser gun to shoot once. The laser beam must enter from one hole and exit from the other one. Each mirror has a preset number vi, which shows the number of points players gain if their laser beam hits that mirror. Also — to make things even funnier — the beam must not hit any mirror more than once.Given the information about the box, your task is to find the maximum score a player may gain. Please note that the reflection obeys the law "the angle of incidence equals the angle of reflection".

The first line of the input contains three space-separated integers hl, hr, n (0 < hl, hr < 100, 0 ≤ n ≤ 100) — the heights of the holes and the number of the mirrors. Next n lines contain the descriptions of the mirrors. The i-th line contains space-separated vi, ci, ai, bi; the integer vi (1 ≤ vi ≤ 1000) is the score for the i-th mirror; the character ci denotes i-th mirror's position — the mirror is on the ceiling if ci equals "T" and on the floor if ci equals "F"; integers ai and bi (0 ≤ ai < bi ≤ 105) represent the x-coordinates of the beginning and the end of the mirror. No two mirrors will share a common point. Consider that the x coordinate increases in the direction from left to right, so the border with the hole at height hl has the x coordinate equal to 0 and the border with the hole at height hr has the x coordinate equal to 105.

The only line of output should contain a single integer — the maximum possible score a player could gain.

NoteThe second sample is depicted above. The red beam gets 10 + 50 + 5 + 35 + 8 + 2 = 110 points and the blue one gets 120.The red beam on the picture given in the statement shows how the laser beam can go approximately, this is just illustration how the laser beam can gain score. So for the second sample there is no such beam that gain score 110.

import qualified Data.List as L
import qualified Data.Set as S
import Data.Ratio
import Control.Monad

type Wall = S.Set (Int, Int, Int)

maybeF f s =
  if S.null s
  then Nothing
  else Just (f s)

maybeMin = maybeF S.findMin
maybeMax = maybeF S.findMax

inside _ Nothing = Nothing
inside p (Just (a, b, c)) =
  if and [p >= a % 1, p <= b % 1]
  then Just (a,b,c)
  else Nothing

passThrough :: Ratio Int -> Wall -> Maybe (Int, Int, Int)
passThrough p walls =
  let
    (small, big) = S.split (round p, round p, 0) walls
  in
    case (p `inside` maybeMax small, p `inside` maybeMin big) of
      (Just x, _) -> Just x
      (_, Just x) -> Just x
      (Nothing, Nothing) -> Nothing

height = 100
width = 100000
intersections :: Int -> Int -> Int -> [Ratio Int]
intersections hl hr k =
  let
    base = case k `mod` 2 of
      0 -> hl + k * height - hr
      1 -> (height - hl) + k * height - hr
  in
    [width * (base - (x * height - hr)) % base | x <- [1..k]]

copyBox :: (Wall, Wall) -> [Wall]
copyBox (upper, lower) = cycle [upper, lower]

solve :: Int -> Int -> Int -> (Wall, Wall) -> Int
solve hl hr n walls =
  case sequence $ filter ((/=) Nothing) [tryHeight x | x <- [1..n]] of
    Just s@(_:_) -> maximum s
    _x -> 0
  where
    tryHeight x = liftM sum . liftM uniqueMirrors . sequence $ zipWith passThrough (intersections hl hr x) (copyBox walls)

uniqueMirrors :: [(Int, Int, Int)] -> [Int]
uniqueMirrors x =
  if and . map (==1) . map length . L.group . L.sort $ x
  then map (\(_, _, a)->a) x
  else []

solve' (hl, hr, n, (up, down)) = solve hl hr n (up, down) `max` solve (100 - hl) (100 - hr) n (down, up)

-- parse :: String -> [Int, Int, Int, (Wall, Wall)]
parse l =
  let
    (t:ts) = map words . lines $ l
    [hl, hr, n] = map read t
    mirrors = foldl collect (S.empty, S.empty) ts
    collect (upper, lower) [v, "T", a, b] = (S.insert (read a, read b, read v) upper, lower)
    collect (upper, lower) [v, "F", a, b] = (upper, S.insert (read a, read b, read v) lower)
  in
    (hl, hr, n, mirrors)

present = show
test = do
  stuff <- readFile "test.in"
  return (solve' . parse $ stuff)
test' = do
  stuff <- readFile "test2.in"
  return (solve' . parse $ stuff)
main = interact $ present . solve' . parse