DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:  where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:  ;  edge  if and only if , and edge ;  the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.

The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.

Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.

NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal.

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main = do
  [n,m] <- map read.words <$> getLine
  arr <- listArray(0,n-1).map readInt.B.words <$> B.getLine
  abcs <- map readInt.B.words <$> B.getContents
  print $ solve arr abcs

solve :: UArray Int Int -> [Int] -> Double
solve arr abcs = go 0.0 abcs
   where
     go !acc (a:b:c:abcs) = go (max acc $ v / e) abcs
      where
       v = fromIntegral . sum $ map (unsafeAt arr.subtract 1) [a,b]
       e = fromIntegral c
     go acc _ = acc

{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}

import Data.List (foldl')
import Control.Applicative ((<$>))
import Data.Array (Array, listArray, (!))
import Control.Monad (replicateM, sequence)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Char8 as Char8

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

getLine' :: IO ByteString
getLine' = ByteString.getLine

parse :: ByteString -> [Int]
parse line =
    case out of Just xs -> xs
                Nothing -> []
    where
    out = sequence . map read' . Char8.words $ line :: Maybe [Int]
    read' :: ByteString -> Maybe Int
    read' = (fst <$>) . Char8.readInt

solve :: Array Int Int -> [[Int]] -> Double
solve a = foldl' max 0 . map den
    where
    den :: [Int] -> Double
    den [i, j, w] = fromIntegral (a ! i + a ! j) / fromIntegral w
    den _ = error "fail!"

main :: IO ()
main = do
    [n, m] <- map read . words <$> getLine
    a <- listArray (1, n) . parse <$> getLine'
    e <- map parse <$> replicateM m getLine'
    print $ solve a e


After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.

The first line contains two space-separated integers n and x (1 ≤ n ≤ 1000, 0 ≤ x ≤ 109). Each of the next n lines contains a character '+' or '-', and an integer di, separated by a space (1 ≤ di ≤ 109). Record "+ di" in i-th line means that a carrier with di ice cream packs occupies i-th place from the start of the queue, and record "- di" means that a child who wants to take di packs stands in i-th place.

Print two space-separated integers — number of ice cream packs left after all operations, and number of kids that left the house in distress.

NoteConsider the first sample.  Initially Kay and Gerda have 7 packs of ice cream.  Carrier brings 5 more, so now they have 12 packs.  A kid asks for 10 packs and receives them. There are only 2 packs remaining.  Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed.  Carrier bring 40 packs, now Kay and Gerda have 42 packs.  Kid asks for 20 packs and receives them. There are 22 packs remaining.

main :: IO()
main = putStrLn . unwords . map show . solve . tail . words =<< getContents

solve :: [String] -> [Integer]
solve (xs:cs) = solve' (read xs) 0 cs

solve' :: Integer -> Integer -> [String] -> [Integer]
solve' x c [] = [x, c]
solve' x c (o:ds:s) | o == "+" = solve' (x + read ds) c s
                    | otherwise = let d = read ds
                                  in if x >= d
                                     then solve' (x - d) c s
                                     else solve' x (c + 1) s

{-# 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, x] <- fmap (map read . words) getLine
  ls <- replicateM n $ (\[a, b] -> (head a, read b)) . words <$> getLine

  let
    (c, s) = f (0, fromIntegral x) ls :: (Int, Int64)
      where
        f (c, s) [] = (c, s)
        f (c, s) (('+', d):xs) = f (c, s+d) xs
        f (c, s) (('-', d):xs)
          | s >= d = f (c, s-d) xs
          | otherwise = f (c+1, s) xs

  putStrLn $ show s ++ " " ++ show c

{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification,
             RankNTypes, FlexibleContexts, DeriveFunctor #-}

import Control.Monad
import Control.Applicative
--import Control.Lens
--import Control.Zipper
import Control.Arrow
import qualified Data.Map as M
import qualified Data.Set as S
import Data.List
--import Control.Comonad
import Data.Monoid
--import Data.Functor.Foldable
--import Test.QuickCheck
import Data.Tree
--import Data.Machine
--import Data.Traversable
--import Data.Distributive
--import Linear
import Control.Monad.Cont

data Ops = Take Integer | Carrier Integer deriving (Eq, Ord, Show, Read)

main = do
  [n, x] <- fmap (map read . words) getLine
  inp <- forM [1..n] $ \_ -> do
         let g ('+':' ':r) = Carrier (read r)
             g ('-':' ':r) = Take (read r)
         fmap g getLine

  let (a, b) = solve inp x
  putStrLn $ show a ++ " " ++ show b

solve :: [Ops] -> Integer -> (Integer, Integer)
solve ops x = res
    where
      res = foldl f (x, 0) ops
          where
            f (x, y) (Carrier d) = (x + d, y)
            f (x, y) (Take d) | x < d = (x, y+1)
                         | otherwise = (x - d, y)

{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification,
             RankNTypes, FlexibleContexts, DeriveFunctor #-}

import Control.Monad
import Control.Applicative
--import Control.Lens
--import Control.Zipper
import Control.Arrow
import qualified Data.Map as M
import qualified Data.Set as S
import Data.List
--import Control.Comonad
import Data.Monoid
--import Data.Functor.Foldable
--import Test.QuickCheck
import Data.Tree
--import Data.Machine
--import Data.Traversable
--import Data.Distributive
--import Linear
import Control.Monad.Cont

data Ops = Take Integer | Carrier Integer deriving (Eq, Ord, Show, Read)

main = do
  [n, x] <- fmap (map read . words) getLine
  inp <- forM [1..n] $ \_ -> do
         let g ('+':' ':r) = Carrier (read r)
             g ('-':' ':r) = Take (read r)
         fmap g getLine

  let (a, b) = solve inp x
  putStrLn $ show a ++ " " ++ show b

solve :: [Ops] -> Integer -> (Integer, Integer)
solve ops x = (numLeft, numDistressed)
    where
      (numLeft, numDistressed) = foldl f (x, 0) ops
      f (n, d) (Carrier c) = (n+c, d)
      f (n, d) (Take m) | n >= m = (n-m, d)
                        | otherwise = (n, d+1)

inp = [Carrier 5,
       Take 10,
       Take 20,
       Carrier 40,
       Take 20]

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString
type Result = [Integer]

solve :: Int -> [Int] -> Result
solve x  = foldl' deal_with [fromIntegral x, 0] . map fromIntegral
    where deal_with [left, distressed] num
            | left + num >= 0 = [left + num, distressed]
            | otherwise       = [left, distressed + 1]

process :: State Reader Result
process = do
    [n, x] <- parse
    ds <- replicateM n $ scan . B.filter (/=' ') <$> parse
    return $ solve x ds

main :: IO ()
main = do
    args <- getArgs
    reader <- if not (null args) && head args == "MINE"
              then B.lines <$> (openFile "input.txt" ReadMode >>= B.hGetContents)
              else B.lines <$> B.getContents
    say $ evalState process reader

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int where

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString where

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer

instance Display Double

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Function
import Data.Ord
import Data.Bits
import Data.Monoid
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main= someFunc
rIn x= fst $ fromJust  $ C.readInteger x
someFunc::IO()
someFunc = C.getLine >>= \ns-> let [n,x] =map rIn $ C.words ns in solve.((:) x)=<<forM [1..n] (\i->rIn.C.filter (/=' ')<$>C.getLine)
solve (x:xs) =(\(t1,t2)->putStr (show t1 ++" "++show t2)) $ foldl (\(b1,b2) a->if b1+a<0 then (b1,b2+1) else (b1+a,b2)) (x,0) xs

module Main where

import Control.Applicative
import Control.Monad

main :: IO ()
main =
    (map read . words <$> getLine :: IO [Integer]) >>=
        \[n, x] -> step n x 0

step :: Integer -> Integer -> Integer -> IO ()
step 0 x d =
    putStrLn (show x ++ " " ++ show d)

step n x d =
    words <$> getLine >>=
        \[c, s] ->
            let
                r = (read s :: Integer)
            in
                if c == "+" then
                    step (n - 1) (x + r) d

                else if x >= r then
                    step (n - 1) (x - r) d

                else
                    step (n - 1) x (d + 1)

import Data.List
import Control.Monad

-- solve 5 7 [('+', 5), ('-', 10), ('-', 20), ('+', 40), ('-', 20)]
-- solve 5 17 [('-', 16), ('-', 2), ('-', 98), ('+', 100), ('-', 98)]

solve :: Integer -> [(Char, Integer)] -> (Integer, Integer)
solve x ops = foldl' updateState (x, 0) ops
    where updateState (total, sads) ('+', amount) = (total + amount, sads)
          updateState (total, sads) ('-', amount) =
              if amount > total
              then (total, sads + 1)
              else (total - amount, sads)

parseOps :: String -> (Char, Integer)
parseOps s = let [[op], amount] = words s
              in (op, read amount)

parseNx :: String -> (Int, Integer)
parseNx s = let [n, x] = words s
            in (read n, read x)

main = do (n, x) <- fmap parseNx getLine
          ops <- replicateM n (fmap parseOps getLine)
          let (total, sads) = solve x ops
          putStr $ show total
          putStr " "
          putStrLn $ show sads

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric
-- import Debug.Trace(trace)

trace x y = y

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

main = interact solve

solve input = (show final_val)++" "++(show distress)
    where
    n_s:x_s:as_w = words input
    n::Int64
    n = read n_s
    x::Int64
    x = read x_s

    entries = parseInput as_w

    (distress, final_val) = foldl' foldOp (0,x) entries

parseInput::[String] -> [(String, Int64)]
parseInput [] = []
parseInput (x:y:xs) = trace ("x is "++x++" Y is "++y) (x, read y):parseInput(xs)

foldOp::(Int64, Int64) -> (String, Int64) -> (Int64, Int64)
foldOp (distress, current) (op, ice_cream)
    | op == "+" = (distress, current+ice_cream)
    | current >= ice_cream = (distress, current-ice_cream)
    | otherwise = (distress+1, current)

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

process::Integer->Integer->[[String]]->String
process x n [] = (show x) ++ " " ++ (show n)
process x n ((a:b:[]):cs) | a=="+" = process (x+bb) n cs
                          | bb<= x = process (x-bb) n cs
                          | otherwise = process x (n+1) cs
      where bb = read b ::Integer

main = do
   [a,b]<-map read <$> words <$> getLine ::IO [Integer]
   d<- map words <$> lines <$> getContents ::IO [[String]]
   putStrLn $ process b 0 d

main = do
  [n,x] <- map read . words <$> getLine
  (x',d) <- foldl process (x,0) . map words . lines <$> getContents
  putStrLn $ show x' ++ " " ++ show d
process (x,d) ["+",y] = (x + read y,d)
process (x,d) ["-",y] | x >= read y = (x - read y,d)
                      | otherwise = (x,d+1)

getInput :: Integer -> IO [(String, Integer)]
getInput 0 = return []
getInput n = do
                inpStr <- getLine
                let w = words inpStr
                let vals = (w !! 0, read $ w !! 1 :: Integer)
                rest <- getInput (n - 1)
                return (vals : rest)

process' :: Integer -> [(String, Integer)] -> (Integer, Integer)
process' n [] = (n, 0)
process' n (("+",x):xs) = process' (n + x) xs
process' n (("-",x):xs) | n >= x = process' (n - x) xs
                        | n < x = (a, b + 1)
                        where (a, b) = process' n xs

main :: IO ()
main = do
        inpStr <- getLine
        let w = words inpStr
        let (n, x) = (read $ w !! 0 :: Integer, read $ w !! 1 :: Integer)
        allInp <- getInput n
        let (a, b) = process' x allInp
        putStrLn $ show a ++ " " ++ show b

getInput :: Integer -> IO [(String, Integer)]
getInput 0 = return []
getInput n = do
                inpStr <- getLine
                let w = words inpStr
                let vals = (w !! 0, read $ w !! 1 :: Integer)
                rest <- getInput (n - 1)
                return (vals : rest)

process :: Integer -> [(String, Integer)] -> (Integer, Integer)
process n [] = (n, 0)
process n ((op,x):xs) = case op of
                            "+" -> process (n + x) xs
                            "-" -> process1 n x xs
                                where process1 n x xs | n >= x = process (n - x) xs
                                                      | n < x = (a, b + 1)
                                                           where (a, b) = process n xs

main :: IO ()
main = do
        inpStr <- getLine
        let w = words inpStr
        let (n, x) = (read $ w !! 0 :: Integer, read $ w !! 1 :: Integer)
        allInp <- getInput n
        let (a, b) = process x allInp
        putStrLn $ show a ++ " " ++ show b

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

main = do
  [n, x] <- map read . words <$> getLine
  [ss, ds] <- transpose . map words <$> replicateM n getLine
  let ans = solve (fromIntegral x) 0 ss (map read ds)
  putStrLn $ show (ans !! 0) ++ " " ++ show (ans !! 1)

solve :: Integer -> Integer -> [String] -> [Integer] -> [Integer]
solve x y [] [] = [x, y]
solve x y (s:ss) (d:ds)
    | s == "+" = solve (x + d) y ss ds
    | s == "-" && d <= x = solve (x - d) y ss ds
    | otherwise = solve x (y + 1) ss ds

main = do
    n:[x] <- return . map read . words =<< getLine
    let dataread = do
	    flag:[amountstr] <- return . words =<< getLine
	    return (flag=="+", read amountstr)
	dataread::IO (Bool, Integer)
    (i,d) <- return . (foldl f (x::Integer,0)) =<< sequence (take (fromIntegral n) $ repeat dataread)
    putStr $ (show i)++" "++show d
	where
	    f (ice, distress) (f,amo) =
		case f	of
		True	-> (ice+amo, distress)
		False	-> if ice >= amo
			    then (ice-amo, distress)
			    else (ice, succ distress)

solve :: [String] -> String
solve (l:ls) = case foldl parser (m, 0) ls of (x, y) -> (show x) ++ " " ++ (show y)
    where [_,m] = map read (words l)
parser :: (Integer, Integer) -> String -> (Integer, Integer)
parser (i,d) (c:' ':str) =
    let k = read str in case c of
    '+' -> (i + k, d)
    '-' -> if k > i then (i, d + 1) else (i - k, d)
main = putStrLn.solve.lines =<< getContents

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

process::(Integer,Integer)->Integer->(Integer,Integer)
process (a,c) d | d>0 = (a+d,c)
                | d<0 && a+d<0= (a,c+1)
		| otherwise = (a+d,c)

tr '+' = ' '
tr x = x

main = do
		[n,x]<- map read <$> words <$> getLine::IO [Integer]
		y1<-map (\z-> [head z]++ (drop 2 z)) <$>lines <$> getContents
		let y2= map (map tr) y1
		let y= map read y2 ::[Integer]
                let (a,c) = foldl process (x,0) y
		putStr  $ show a
		putStr " "
		putStrLn $ show c

import Control.Applicative
import Control.Monad.State
import Control.Arrow

runCommand :: (String, Integer) -> State (Integer, Integer) ()
runCommand ("+", n) = modify $ first (+n)
runCommand ("-", n) = do
  x <- fst <$> get
  if x >= n
    then modify $ first (+ (-n))
    else modify $ second (+1)

getCommand :: IO (String, Integer)
getCommand = do
  [a, b] <- words <$> getLine
  return $ (a, read b)

main = do
  [n, x] <- map read . words <$> getLine
  commands <- replicateM n getCommand
  let (a, b) = execState (mapM_ runCommand commands) (fromIntegral x, 0)
  putStrLn $ show a ++ " " ++ show b

process :: Integer -> [(Char, Integer)] -> (Integer, Integer)
process x fs = foldl f (x,0) fs
    where
        f (x,y) (c,d)
            | c == '-' = if x < d then (x,y+1) else (x-d,y)
            | otherwise = (x+d,y)

readInt :: String -> Integer
readInt = read

processLine :: String -> (Char, Integer)
processLine line = (char,d)
    where
        [char:_,dStr] = words line
        d = read dStr

main :: IO ()
main = do
    line <- getLine
    let [n,x] = map readInt (words line)
    fs <- fmap (map processLine.lines) getContents
    let (x',y') = process x fs
    putStrLn $ show x' ++ " " ++ show y'

myShow :: (Integer, Integer) -> String
myShow (a, b) = show a ++ " " ++ show b

simulate :: [[String]] -> Integer -> Integer -> (Integer, Integer)
simulate [] x k = (x, k)
simulate (["+", am]:rest) x k = simulate rest (x + read am) k
simulate (["-", am]:rest) x k
  | read am <= x = simulate rest (x - read am) k
  | otherwise    = simulate rest x (k + 1)

solve :: String -> String
solve str =
  let (h:b)  = lines str
      [n, x] = map read . words $ h
      queue  = map words $ take (fromIntegral n) b
  in myShow $ simulate queue x 0

main :: IO()
main = interact solve

{-# 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, x] <- fmap (map read . words) getLine
  ls <- replicateM n $ (\[a, b] -> (head a, read b)) . words <$> getLine

  let
    (c, s) = f (0, x) ls
      where
        f (c, s) [] = (c, s)
        f (c, s) (('+', d):xs) = f (c, s+d) xs
        f (c, s) (('-', d):xs)
          | s >= d = f (c, s-d) xs
          | otherwise = f (c+1, s) xs

  putStrLn $ show s ++ " " ++ show c

{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification,
             RankNTypes, FlexibleContexts, DeriveFunctor #-}

import Control.Monad
import Control.Applicative
--import Control.Lens
--import Control.Zipper
import Control.Arrow
import qualified Data.Map as M
import qualified Data.Set as S
import Data.List
--import Control.Comonad
import Data.Monoid
--import Data.Functor.Foldable
--import Test.QuickCheck
import Data.Tree
--import Data.Machine
--import Data.Traversable
--import Data.Distributive
--import Linear
import Control.Monad.Cont

data Ops = Take Int | Carrier Int deriving (Eq, Ord, Show, Read)

main = do
  [n, x] <- fmap (map read . words) getLine
  inp <- forM [1..n] $ \_ -> do
         let g ('+':' ':r) = Carrier (read r)
             g ('-':' ':r) = Take (read r)
         fmap g getLine

  let (a, b) = solve inp x
  putStrLn $ show a ++ " " ++ show b

solve :: [Ops] -> Int -> (Int, Int)
solve ops x = res
    where
      res = foldl f (x, 0) ops
          where
            f (x, y) (Carrier d) = (x + d, y)
            f (x, y) (Take d) | x < d = (x, y+1)
                         | otherwise = (x - d, y)

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString
type Result = [Int]

solve :: Int -> [Int] -> Result
solve x  = foldl' deal_with [x, 0]
    where deal_with [left, distressed] num
            | left + num >= 0 = [left + num, distressed]
            | otherwise       = [left, distressed + 1]

process :: State Reader Result
process = do
    [n, x] <- parse
    ds <- replicateM n $ scan . B.filter (/=' ') <$> parse
    return $ solve x ds

main :: IO ()
main = do
    args <- getArgs
    reader <- if not (null args) && head args == "MINE"
              then B.lines <$> (openFile "input.txt" ReadMode >>= B.hGetContents)
              else B.lines <$> B.getContents
    say $ evalState process reader

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int where

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString where

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Double

module Main where

import Control.Applicative
import Control.Monad

main :: IO ()
main =
    (map read . words <$> getLine :: IO [Int]) >>=
        \[n, x] -> step n x 0

step :: Int -> Int -> Int -> IO ()
step 0 x d =
    putStrLn (show x ++ " " ++ show d)

step n x d =
    words <$> getLine >>=
        \[c, s] ->
            let
                r = (read s :: Int)
            in
                if c == "+" then
                    step (n - 1) (x + r) d

                else if x >= r then
                    step (n - 1) (x - r) d

                else
                    step (n - 1) x (d + 1)

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric
-- import Debug.Trace(trace)

trace x y = y

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

main = interact solve

solve input = (show final_val)++" "++(show distress)
    where
    n_s:x_s:as_w = words input
    n::Int
    n = read n_s
    x::Int
    x = read x_s

    entries = parseInput as_w

    (distress, final_val) = foldl' foldOp (0,x) entries

parseInput::[String] -> [(String, Int)]
parseInput [] = []
parseInput (x:y:xs) = trace ("x is "++x++" Y is "++y) (x, read y):parseInput(xs)

foldOp::(Int, Int) -> (String, Int) -> (Int, Int)
foldOp (distress, current) (op, ice_cream)
    | op == "+" = (distress, current+ice_cream)
    | current >= ice_cream = (distress, current-ice_cream)
    | otherwise = (distress+1, current)

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

process::Int->Int->[[String]]->String
process x n [] = (show x) ++ " " ++ (show n)
process x n ((a:b:[]):cs) | a=="+" = process (x+bb) n cs
                          | bb<= x = process (x-bb) n cs
                          | otherwise = process x (n+1) cs
      where bb = read b ::Int

main = do
   [a,b]<-map read <$> words <$> getLine ::IO [Int]
   d<- map words <$> lines <$> getContents ::IO [[String]]
   putStrLn $ process b 0 d

main = do
    n:[x] <- return . map read . words =<< getLine
    let dataread = do
	    flag:[amountstr] <- return . words =<< getLine
	    return (flag=="+", read amountstr)
	dataread::IO (Bool, Int)
    (i,d) <- return . (foldl f (x,0)) =<< sequence (take n $ repeat dataread)
    putStr $ (show i)++" "++show d
	where
	    f (ice, distress) (f,amo) =
		case f	of
		True	-> (ice+amo, distress)
		False	-> if ice >= amo
			    then (ice-amo, distress)
			    else (ice, succ distress)

solve :: [String] -> String
solve (l:ls) = case foldl parser (m, 0) ls of (x, y) -> (show x) ++ " " ++ (show y)
    where [_,m] = map read (words l)
parser :: (Int, Int) -> String -> (Int, Int)
parser (i,d) (c:' ':str) =
    let k = read str in case c of
    '+' -> (i + k, d)
    '-' -> if k > i then (i, d + 1) else (i - k, d)
main = putStrLn.solve.lines =<< getContents

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

process (a,c) d | d>0 = (a+d,c)
                | d<0 && a+d<0= (a,c+1)
		| otherwise = (a+d,c)

tr '+' = ' '
tr x = x

main = do
		[n,x]<- map read <$> words <$> getLine::IO [Int]
		y1<-map (\z-> [head z]++ (drop 2 z)) <$>lines <$> getContents
		let y2= map (map tr) y1
		let y= map read y2 ::[Int]
                let (a,c) = foldl process (x,0) y
		putStr  $ show a
		putStr " "
		putStrLn $ show c

import Control.Applicative
import Control.Monad.State
import Control.Arrow

runCommand :: (String, Int) -> State (Int, Int) ()
runCommand ("+", n) = modify $ first (+n)
runCommand ("-", n) = do
  x <- fst <$> get
  if x >= n
    then modify $ first (+ (-n))
    else modify $ second (+1)

getCommand :: IO (String, Int)
getCommand = do
  [a, b] <- words <$> getLine
  return $ (a, read b)

main = do
  [n, x] <- map read . words <$> getLine
  commands <- replicateM n getCommand
  let (a, b) = execState (mapM_ runCommand commands) (x, 0)
  putStrLn $ show a ++ " " ++ show b

process :: Int -> [(Char, Int)] -> (Int, Int)
process x fs = foldl f (x,0) fs
    where
        f (x,y) (c,d)
            | c == '-' = if x < d then (x,y+1) else (x-d,y)
            | otherwise = (x+d,y)

readInt :: String -> Int
readInt = read

processLine :: String -> (Char, Int)
processLine line = (char,d)
    where
        [char:_,dStr] = words line
        d = read dStr

main :: IO ()
main = do
    line <- getLine
    let [n,x] = map readInt (words line)
    fs <- fmap (map processLine.lines) getContents
    let (x',y') = process x fs
    putStrLn $ show x' ++ " " ++ show y'


Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.

The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.

A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.

NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement.   $$$(1,3)$$$, $$$(2,3)$$$  $$$(2,2)$$$, $$$(2,3)$$$  $$$(2,1)$$$, $$$(2,2)$$$

{-# LANGUAGE BangPatterns #-}
import           Control.Applicative
import           Control.Monad
import           Data.List
main = do
  [n, _, k]  <- map read.words <$> getLine
  css <- replicateM n getLine
  print $ solve k css

solve :: Int -> [String] -> Int
solve k css
  | k == 1 = sum $ map step css
  | otherwise =  sum (map step css) + sum (map step (transpose css))
  where
    step cs = sum [l - k + 1 | g@('.':_)<-group cs, let !l=length g, l >= k]

import Control.Monad
import Data.List

doit :: Int -> Int -> String -> Int
doit k sz l = length . filter (>= k) $ scanl f 0 l
  where f sz '*' = 0
        f sz '.' = sz + 1

main = do
  [n,m,k] <- fmap (fmap read . words) getLine
  l <- replicateM n getLine
  print $ if k == 1
          then sum . map (length . filter (=='.')) $ l
          else sum . map sum . map (map (doit k 0)) $ [l, transpose l]

import Control.Monad
import Data.List

doit :: Int -> Int -> String -> Int
doit _ _ [] = 0
doit k sz ('*':xs) = doit k 0 xs
doit k sz ('.':xs) = doit k (sz + 1) xs + cur
  where cur = if sz + 1 >= k then 1 else 0

main = do
  [n,m,k] <- fmap (fmap read . words) getLine
  l <- replicateM n getLine
  print $ if k == 1
          then sum . map (length . filter (=='.')) $ l
          else sum . map sum . map (map (doit k 0)) $ [l, transpose l]


There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i, j) (i < j) exists such that  or , where  denotes intersection of sets, and  denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup.

If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower).

NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below.  For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column.

{-# LANGUAGE ViewPatterns #-}
import Data.List
import Data.Bits
import Data.Int
import Data.Bool
main = interact exec
exec = bool "No" "Yes" . solve . drop 2 . words
solve = all (\(a, b) -> a .&. b == 0 || a == b) . pairs . map comp
pairs xs = [(a, b) | (a:bs) <- tails xs, b <- bs]
comp = foldl' (\s (i, x) -> if x == '#' then setBit s i else s) (0 :: Int64) . zip [0..]


Alice and Bob are playing a game on a sequence $$$a_1, a_2, \dots, a_n$$$ of length $$$n$$$. They move in turns and Alice moves first.In the turn of each player, he or she should select an integer and remove it from the sequence. The game ends when there is no integer left in the sequence. Alice wins if the sum of her selected integers is even; otherwise, Bob wins. Your task is to determine who will win the game, if both players play optimally.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$), indicating the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$), indicating the elements of the sequence.

For each test case, output "Alice" (without quotes) if Alice wins and "Bob" (without quotes) otherwise.

NoteIn the first and second test cases, Alice always selects two odd numbers, so the sum of her selected numbers is always even. Therefore, Alice always wins.In the third test case, Bob has a winning strategy that he always selects a number with the same parity as Alice selects in her last turn. Therefore, Bob always wins.In the fourth test case, Alice always selects two even numbers, so the sum of her selected numbers is always even. Therefore, Alice always wins.

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let od = length . filter odd. map (read::String -> Int) . words $ input
        putStrLn .toShow $ odd (div od 2) && even od || odd n && odd (div (od+1) 2)
    return ()

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = read <$> getLine >>=
        \n -> map read . words <$> getLine >>=
        print . whoWins n

data Player = Alice | Bob deriving (Eq, Show)

whoWins :: Int -> [Int] -> Player
whoWins n as = let o = foldl (\acc e -> if (mod e 2 == 0) then acc else acc+1) 0 as
                   p x = mod x 2 == 0
                   k = div n 2
                   m = div o 2
               in
                 case (p n, p o) of
                   (_, True) -> if (mod m 2 == 0) then Alice else Bob
                   (True, False) -> Alice
                   (False, False) -> if (mod (m+1) 2 == 0) then Alice else Bob

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
            od = length $ filter odd a

        putStrLn .toShow $ od==2 || (od/=1 || odd n) && odd (div (od+1) 2)
    return ()

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
            od = length $ filter odd a

        putStrLn .toShow $ od==2 || od==1 && odd n || odd (div (od+1) 2)
    return ()

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
            od = length $ filter odd a

        putStrLn .toShow $ od==2 || od==1 && odd n || odd n  && odd (div (od+1) 2)
    return ()

import Control.Monad
import Data.List

toShow True = "Bob"
toShow False = "Alice"

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
            od = length $ filter odd a

        putStrLn .toShow $ od==2 || od==1 && odd n
    return ()

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = read <$> getLine >>=
        \n -> map read . words <$> getLine >>=
        print . whoWins n

data Player = Alice | Bob deriving (Eq, Show)

whoWins :: Int -> [Int] -> Player
whoWins n as = let o = foldl (\acc e -> if (mod e 2 == 0) then acc else acc+1) 0 as
                   p x = mod x 2 == 0
                   k = div n 2
                   m = div o 2
               in
                 case (p n, p o) of
                   (_, True) -> if (mod m 2 == 0) then Alice else Bob
                   (True, False) -> Alice
                   (False, False) -> if (k > m)
                                     then Alice
                                     else if (mod (m+1) 2 == 0) then Alice else Bob


There are $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. For the one move you can choose any even value $$$c$$$ and divide by two all elements that equal $$$c$$$.For example, if $$$a=[6,8,12,6,3,12]$$$ and you choose $$$c=6$$$, and $$$a$$$ is transformed into $$$a=[3,8,12,3,3,12]$$$ after the move.You need to find the minimal number of moves for transforming $$$a$$$ to an array of only odd integers (each element shouldn't be divisible by $$$2$$$).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of integers in the sequence $$$a$$$. The second line contains positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$.

For $$$t$$$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $$$2$$$).

NoteIn the first test case of the example, the optimal sequence of moves can be as follows:  before making moves $$$a=[40, 6, 40, 3, 20, 1]$$$;  choose $$$c=6$$$;  now $$$a=[40, 3, 40, 3, 20, 1]$$$;  choose $$$c=40$$$;  now $$$a=[20, 3, 20, 3, 20, 1]$$$;  choose $$$c=20$$$;  now $$$a=[10, 3, 10, 3, 10, 1]$$$;  choose $$$c=10$$$;  now $$$a=[5, 3, 5, 3, 5, 1]$$$ — all numbers are odd. Thus, all numbers became odd after $$$4$$$ moves. In $$$3$$$ or fewer moves, you cannot make them all odd.

import qualified Data.Set as Set
import Control.Monad

solve :: Set.Set Int -> Int -- only for even elements
solve s
  |Set.null s = 0
  |otherwise = if odd m2 then 1 + solve s' else 1 + solve (Set.insert m2 s')
  where
    m = Set.findMax s
    m2 = m `div` 2
    s' = Set.delete m s

routine :: IO ()
routine = do
  _ <- getLine
  l <-(filter even . map read . words) <$> getLine
  print $ solve $ Set.fromList l

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

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as ST
import Control.Monad
import Data.List
import Data.Maybe

solve xs = loop st
  where
    st = foldl' (flip ST.insert) ST.empty xs
    loop st
      | ST.null st = 0
      | m == 0 = 1 + loop (ST.insert d st')
      | otherwise = loop st'
      where
        m = a `mod` 2
        d = a `div` 2
        (a,st') = ST.deleteFindMax st

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    n <- readLn :: IO Int
    xs <- map read . words <$> getLine :: IO [Int]
    print $ solve xs

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as ST
import Control.Monad
import Data.List
import Data.Maybe

solve xs = loop st
  where
    st = foldl' (flip ST.insert) ST.empty xs
    loop st
      | ST.null st = 0
      | m == 0 = 1 + loop (ST.insert d st')
      | otherwise = loop st'
      where
        m = a `mod` 2
        d = a `div` 2
        (a,st') = ST.deleteFindMax st

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    n <- readLn :: IO Int
    xs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO [Int]
    print $ solve xs

{-# LANGUAGE Strict #-}

import qualified Data.ByteString.Char8 as B
import qualified Data.Map as MP
import Data.Array
import Data.Maybe
import Data.Maybe
import Control.Monad

count :: MP.Map Int Int -> Int -> Int -> MP.Map Int Int
count mp x acc =
    case MP.lookup k mp of
      Just _ -> MP.adjust (max v) k mp
      Nothing -> MP.insert k v mp
  where
    (k,v) = loop x (0,0)
    loop a (k,v)
      | m == 1 = (d,v)
      | otherwise = loop d (k,v+1)
      where
        d = a `div` 2
        m = a `mod` 2

solve arr n = MP.foldl (+) 0 mp
  where
    mp = loop 0 MP.empty
    loop i m
      | i > n = m
      | otherwise =
        let
          v = arr ! i
          m' = count m v 0
        in
          loop (i+1) m'
main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    n <- readLn :: IO Int
    arr <- listArray (0, n-1) <$> map (fst . fromJust . B.readInt) . B.words <$> B.getLine :: IO (Array Int Int)
    print $ solve arr (n-1)


One university has just found out about a sport programming contest called ACM ICPC v2.0. This contest doesn't differ much from the well-known ACM ICPC, for example, the participants are not allowed to take part in the finals more than two times. However, there is one notable difference: the teams in the contest should consist of exactly n participants.Having taken part in several ACM ICPC v2.0 finals and having not won any medals, the students and the university governors realized that it's high time they changed something about the preparation process. Specifically, as the first innovation it was decided to change the teams' formation process. Having spent considerable amount of time on studying the statistics of other universities' performance, they managed to receive some interesting information: the dependence between the probability of winning a medal and the number of team members that participated in the finals in the past. More formally, we know n + 1 real numbers p0 ≤ p1 ≤ ... ≤ pn, where pi is the probability of getting a medal on the finals if the team has i participants of previous finals, and other n - i participants arrived to the finals for the first time.Despite such useful data, the university governors are unable to determine such team forming tactics that would provide the maximum probability of winning a medal at ACM ICPC v2.0 finals on average (we are supposed to want to provide such result to the far future and we are also supposed to have an endless supply of students). And how about you, can you offer such optimal tactic? At the first stage the university governors want to know the value of maximum average probability.More formally, suppose that the university sends a team to the k-th world finals. The team has ak participants of previous finals (0 ≤ ak ≤ n). Since each person can participate in the finals no more than twice, the following condition must be true: . Your task is to choose sequence  so that the limit Ψ exists and it's value is maximal:As  is an infinite sequence, you should only print the maximum value of the Ψ limit.

The first line contains an integer n (3 ≤ n ≤ 100), n is the number of team participants. The second line contains n + 1 real numbers with no more than 6 digits after decimal point pi (0 ≤ i ≤ n, 0 ≤ pi ≤ 1) — the probability of that the team will win a medal if it contains i participants who has already been on the finals. Also the condition pi ≤ pi + 1 should be fulfilled for all 0 ≤ i ≤ n - 1.

Print the only real number — the expected average number of medals won per year if the optimal strategy is used. The result may have absolute or relative error 10 - 6.

NoteIn the second test, no matter what participants the team contains, it is doomed to be successful.

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    n <- readInt
    prob <- replicateM (n + 1) readDouble
    return (n, prob)
  where
    readDouble = read . BS.unpack <$> readString :: State ByteString Double
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = print =<< solve . evalState parseInput <$> BS.getContents

solve :: (Int, [Double]) -> Double
solve (n, prob) = maximum answers
  where
    lst = zip [0..] prob
    answers = [solveCase n x y | x <- lst, y <- lst]

solveCase :: Int -> (Int, Double) -> (Int, Double) -> Double
solveCase n (i, pi) (j, pj)
    | i' >= 0 && j' >= 0 = max pi pj
    | i' == 0            = pi
    | j' == 0            = pj
    | i' < 0 && j' < 0   = - 1.0e9
    | otherwise          = (pi * jnum + pj * inum) / (inum + jnum)
  where
    i' = n - 2 * i
    j' = n - 2 * j

    inum = fromIntegral $ abs i' :: Double
    jnum = fromIntegral $ abs j' :: Double

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

class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
	s <- get
	put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
	s <- get
	return (f s)

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

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

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

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

instance MonadState s (State s) where
	get   = State $ \s -> (s, s)
	put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State


Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?

The first line contains string a, the second line contains string b, and the third line contains string c (1 ≤ |a|, |b|, |c| ≤ 105, where |s| denotes the length of string s). All three strings consist only of lowercase English letters.  It is possible that b and c coincide.

Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.

NoteIn the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1 – 2 (ab), 3 – 4 (ab), 5 – 7 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc.

alphabet :: String
alphabet = ['a'..'z']

singleton :: a -> [a]
singleton x = [x]

type Count  = [Int]
type Result = (Int, Int, Count)

count :: String -> Count
count s = map count' alphabet
          where count' c = length . filter (== c) $ s

occur :: Count -> Count -> Int
occur p = minimum . map (uncurry $ flip div) . filter ((> 0) . fst) . zip p

exclude :: Int -> Count -> Count -> Count
exclude n = zipWith (\a c -> c - n * a)

build :: String -> String -> Result -> String
build a b (xy, x, c) = concat $ concatMap (uncurry replicate) components
                       where y          = xy - x
                             components = [(x, a), (y, b)] ++ zip c (map singleton alphabet)

compute :: Count -> Count -> Count -> Int -> Result
compute a b c i = (i + j, i, c'')
                  where c'  = exclude i a c
                        j   = occur b c'
                        c'' = exclude j b c'

solve :: String -> String -> String -> String
solve a' b' c' = build a' b' best
                 where [a, b, c] = map count [a', b', c']
                       n         = occur a c
                       best      = maximum [compute a b c i | i <- [0..n]]

main :: IO ()
main = do
    a <- getLine
    b <- getLine
    c <- getLine
    putStrLn $ solve b c a


You are both a shop keeper and a shop assistant at a small nearby shop. You have $$$n$$$ goods, the $$$i$$$-th good costs $$$a_i$$$ coins.You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $$$n$$$ goods you have.However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all $$$n$$$ goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.So you need to find the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100)$$$ — the number of goods. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$), where $$$a_i$$$ is the price of the $$$i$$$-th good.

For each query, print the answer for it — the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.

handle = do
	line <- getLine
	l2 <- getLine
	let n = read line :: Int
	let ar = map read (words l2) :: [Int]
	let s = sum ar
	let res = (s+n-1) `div` n
	putStrLn (show res)

handleCase 0 = return ()
handleCase n = do
	handle
	handleCase (n-1)

main = do
	lineq <- getLine
	let q = (read lineq :: Int)
	handleCase q
	{-
	line2 <- getLine
	let n = (read line :: Int)
	let x = n+1
	let s = show x
	let z = words line2
	let ar = map read z :: [Int]
	let s2 = map (show . (+ 1)) ar
	putStrLn s
	putStrLn (concat s2) -}

import Control.Monad (replicateM_)
import Control.Arrow ((>>>))
main :: IO ()
main = do
  q <- read <$> getLine ::IO Int
  replicateM_ q solve
solve :: IO()
solve = do
  n <- read <$> getLine :: IO Int
  xs <- (words >>> map read) <$> getLine
  print $ ceiling $ fromIntegral (sum xs) / fromIntegral n

import Control.Monad
main = do
  q <- readLn
  replicateM_ q $ do
    n <- readLn
    s <- sum . map read . words <$> getLine
    print $ (s + n - 1) `div` n

import Control.Monad
import Data.Ratio

solve :: [Int] -> Int
solve nums = ceiling (sum nums % length nums)

main = do
  numQueries <- read <$> getLine
  replicateM numQueries $ do
    _ <- getLine
    prices <- fmap read <$> words <$> getLine
    print $ solve prices

import Control.Monad ( replicateM )

main = do
  n <- readLn
  replicateM n $ do
    getLine
    arr <- fmap (fmap read . words) getLine
    print $ ceiling $ fromIntegral (sum arr) / fromIntegral (length arr)

module Main where

import Control.Monad
import Data.List

cdiv num den = (num + den - 1) `div` den
avg vals = let l = length vals in cdiv (sum vals) l

main :: IO ()
main = do
    let ri = read::String->Int
    q <- ri <$> getLine

    replicateM_ q $ do
        _ <- ri <$> getLine
        vals <- fmap ri . words <$> getLine

        print $ avg vals
        return ()
    return ()

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

onecase= do
	   r<-read <$>getLine ::IO Int
	   a<-sum <$> map read <$> words <$> getLine::IO Int
           let ans =  div a r+ if mod a r>0 then 1 else 0
	   print ans

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

import Control.Monad
divUp a b
	| a `mod` b == 0 = a `div` b
	| otherwise      = (a `div` b) + 1

doQuery = do
	nStr <- getLine
	listStr <- getLine
	let ans = (sum $ map read $ words listStr) `divUp` (read nStr)
	putStrLn $ show ans

main = do
	q <- getLine
	replicateM_ (read q) doQuery

import Control.Monad ( replicateM )

main = do
  n <- readLn
  replicateM n $ do
    getLine
    arr <- fmap (fmap read . words) getLine
    print $ sum arr `div` length arr

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

onecase= do
	   r<-read <$>getLine ::IO Int
	   a<-sum <$> map read <$> words <$> getLine::IO Int
           let ans = 1+ div a r
	   print ans

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


Polycarp is flying in the airplane. Finally, it is his favorite time — the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat m, that means, he will be the m-th person to get food.The flight menu has k dishes in total and when Polycarp boarded the flight, he had time to count the number of portions of each dish on board. Thus, he knows values a1, a2, ..., ak, where ai is the number of portions of the i-th dish.The stewardess has already given food to m - 1 passengers, gave Polycarp a polite smile and asked him what he would prefer. That's when Polycarp realized that they might have run out of some dishes by that moment. For some of the m - 1 passengers ahead of him, he noticed what dishes they were given. Besides, he's heard some strange mumbling from some of the m - 1 passengers ahead of him, similar to phrase 'I'm disappointed'. That happened when a passenger asked for some dish but the stewardess gave him a polite smile and said that they had run out of that dish. In that case the passenger needed to choose some other dish that was available. If Polycarp heard no more sounds from a passenger, that meant that the passenger chose his dish at the first try.Help Polycarp to find out for each dish: whether they could have run out of the dish by the moment Polyarp was served or that dish was definitely available.

Each test in this problem consists of one or more input sets. First goes a string that contains a single integer t (1 ≤ t ≤ 100 000) — the number of input data sets in the test. Then the sets follow, each set is preceded by an empty line. The first line of each set of the input contains integers m, k (2 ≤ m ≤ 100 000, 1 ≤ k ≤ 100 000) — the number of Polycarp's seat and the number of dishes, respectively. The second line contains a sequence of k integers a1, a2, ..., ak (1 ≤ ai ≤ 100 000), where ai is the initial number of portions of the i-th dish. Then m - 1 lines follow, each line contains the description of Polycarp's observations about giving food to a passenger sitting in front of him: the j-th line contains a pair of integers tj, rj (0 ≤ tj ≤ k, 0 ≤ rj ≤ 1), where tj is the number of the dish that was given to the j-th passenger (or 0, if Polycarp didn't notice what dish was given to the passenger), and rj — a 1 or a 0, depending on whether the j-th passenger was or wasn't disappointed, respectively. We know that sum ai equals at least m, that is,Polycarp will definitely get some dish, even if it is the last thing he wanted. It is guaranteed that the data is consistent. Sum m for all input sets doesn't exceed 100 000. Sum k for all input sets doesn't exceed 100 000.

For each input set print the answer as a single line. Print a string of k letters "Y" or "N". Letter "Y" in position i should be printed if they could have run out of the i-th dish by the time the stewardess started serving Polycarp.

NoteIn the first input set depending on the choice of the second passenger the situation could develop in different ways:  If he chose the first dish, then by the moment the stewardess reaches Polycarp, they will have run out of the first dish;  If he chose the fourth dish, then by the moment the stewardess reaches Polycarp, they will have run out of the fourth dish;  Otherwise, Polycarp will be able to choose from any of the four dishes. Thus, the answer is "YNNY".In the second input set there is, for example, the following possible scenario. First, the first passenger takes the only third dish, then the second passenger takes the second dish. Then, the third passenger asks for the third dish, but it is not available, so he makes disappointed muttering and ends up with the second dish. Then the fourth passenger takes the fourth dish, and Polycarp ends up with the choice between the first, fourth and fifth dish.Likewise, another possible scenario is when by the time the stewardess comes to Polycarp, they will have run out of either the first or the fifth dish (this can happen if one of these dishes is taken by the second passenger). It is easy to see that there is more than enough of the fourth dish, so Polycarp can always count on it. Thus, the answer is "YYYNY".

{-# LANGUAGE ScopedTypeVariables #-}
import Control.Applicative
import Control.Monad
import Data.Array.Unboxed
import Data.Maybe
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  (re:_) <- readInts
  replicateM_ re $ do
    _ <- readInts
    (m:n:_) <- readInts
    (a :: UArray Int Int) <- listArray (1, n) <$> readInts
    b <- replicateM (m-1) $ do
      (i:j:_) <- readInts
      return (i, j)
    let (x, y) = span ((==0) . snd) b
        zx = length $ filter ((==0) . fst) x
        zy = length $ filter ((==0) . fst) b
        cx = accum (-) a [(i, 1) | (i, _) <- x, i /= 0]
        cy = accum (-) cx [(i, 1) | (i, _) <- y, i /= 0]
        v
          | null y = 0
          | otherwise = minimum [c | (i, c) <- assocs cx, cx!i == cy!i]
        f i = (cx!i <= zx && cx!i == cy!i) || cy!i <= zy - v
    putStrLn [if f i then 'Y' else 'N' | i <- [1..n]]
  where
  readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

{-# LANGUAGE ScopedTypeVariables #-}
import Control.Applicative
import Control.Monad
import Data.Array.Unboxed
import Data.Maybe
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  (re:_) <- readInts
  replicateM_ re $ do
    _ <- readInts
    (m:n:_) <- readInts
    (a :: UArray Int Int) <- listArray (1, n) <$> readInts
    b <- replicateM (m-1) $ do
      (i:j:_) <- readInts
      return (i, j)
    let (x, y) = span ((==0) . snd) b
        zx = length $ filter ((==0) . fst) x
        zy = length $ filter ((==0) . fst) b
        cx = accum (-) a [(i, 1) | (i, _) <- x, i /= 0]
        cy = accum (-) cx [(i, 1) | (i, _) <- y, i /= 0]
        v
          | null y = 0
          | otherwise = minimum [c | (i, c) <- assocs cx, cx!i == cy!i]
    putStrLn [if cx!i <= zx || cy!i <= zy - v then 'Y' else 'N' | i <- [1..n]]
  where
  readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

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

main :: IO ()
main = do
  (re:_) <- readInts
  replicateM_ re $ do
    _ <- readInts
    (m:n:_) <- readInts
    a <- listArray (1, n) <$> readInts
    b <- replicateM (m-1) $ do
      (i:j:_) <- readInts
      return (i, j)
    let (x, y) = span ((==0) . snd) b
        z = length $ filter ((==0) . fst) b
        cx = accum (-) a [(i, 1) | (i, _) <- x, i /= 0]
        cy = accum (-) cx [(i, 1) | (i, _) <- y, i /= 0]
        (v, k)
          | null y = (0, 0)
          | otherwise = minimum [(c, i) | (i, c) <- assocs cx, cx!i == cy!i]
    putStrLn [if i == k || cy!i <= z - v then 'Y' else 'N' | i <- [1..n]]
  where
  readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine


You are given an array $$$a_1, a_2, \ldots, a_n$$$.In one operation you can choose two elements $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.

Print "YES" if it is possible to make all elements zero, otherwise print "NO".

NoteIn the first example, you can make all elements equal to zero in $$$3$$$ operations:   Decrease $$$a_1$$$ and $$$a_2$$$,  Decrease $$$a_3$$$ and $$$a_4$$$,  Decrease $$$a_3$$$ and $$$a_4$$$ In the second example, one can show that it is impossible to make all elements equal to zero.

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

main::IO()
main = do
    n <- getLine
    a <- map read . words <$> getLine
    let suma = foldl (+) 0 a
    let maxa = maximum a
    if suma `rem` 2 == 1
        then putStrLn "NO"
        else if suma `div` 2 < maxa
            then putStrLn "NO"
            else putStrLn "YES"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Integer) <$> words num
  let sum_ = sum nums
  let max_ = maximum nums
  if (mod sum_ 2 == 0) && ((2 * max_) <= sum_)
     then putStrLn "YES"
  else putStrLn "NO"

    import Control.Monad
    import Data.String
    readListRec :: Integer -> IO [String]
    readListRec lineNumber =
      if (lineNumber == 0)
      then return []
      else
        getLine >>= \newLine ->
        (newLine :) <$> readListRec(lineNumber - 1)

    parseLineToInt :: String -> [Integer]
    parseLineToInt data_s = do
      (read::String->Integer) <$> (words data_s)

    countLetters :: [Char] -> Char -> Int
    countLetters array_ char_ = length (filter (==char_) array_)

    scoreCount :: [String] -> Int -> [Int]
    scoreCount answList questionNumber =
      if (0 == length (answList!!0))
      then []
      else do
        let currentAnswer = (!!0) <$> answList
        let restAnswers = (drop 1) <$> answList
        let answers = ['A','B','C','D','E']
        let maxScore = maximum ((countLetters currentAnswer) <$> answers)
        maxScore : scoreCount restAnswers (questionNumber + 1)

    myDot :: [Int] -> [Int] -> Int
    myDot x y = sum (zipWith (*) x y)

    main = do
      getLine
      dataInts <- getLine
      let array_ = parseLineToInt dataInts
      let sum_ = sum array_
      let max_ = maximum array_
      if ((mod sum_  2 == 0) &&((2 * max_) <= sum_))
      then putStrLn $ "YES"
      else putStrLn $ "NO"

solv :: [Integer] -> Bool
solv l = let s = sum l in
             let mx = maximum l in
                 (mod s 2 == 0) && (mx <= (div s 2))

main = do
  l <- getLine
  let n = (read l) :: Int
  inp <- getLine
  let inn = map read $ words inp
  let res = solv inn
  putStrLn $ if res then "YES" else "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  if ( (== 0) $ mod (sum nums) 2) && ((2*) $ maximum nums) <= sum nums
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  if ( (== 0) $ mod (sum nums) 2) && maximum nums <= sum nums
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  let sum_ = sum nums
  let max_ = maximum nums
  if (mod sum_ 2 == 0) && ((2 * max_) <= sum_)
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  let sum_ = sum nums
  let max_ = maximum nums
  if (sum_ `mod` 2 == 0) && (2 * max_ <= sum nums)
     then putStrLn "YES"
  else putStrLn "NO"

main :: IO ()
main = do
  _ <- getLine
  num <- getLine
  let nums = (read :: String -> Int) <$> words num
  if ( (== 0) $ mod (sum nums) 2) && maximum nums <= sum nums
     then print "YES"
  else print "NO"

import Control.Monad
import Data.String
readListRec :: Int -> IO [String]
readListRec lineNumber =
  if (lineNumber == 0)
  then return []
  else
    getLine >>= \newLine ->
    (newLine :) <$> readListRec(lineNumber - 1)

parseLineToInt :: String -> [Int]
parseLineToInt data_s = do
  (read::String->Int) <$> (words data_s)

countLetters :: [Char] -> Char -> Int
countLetters array_ char_ = length (filter (==char_) array_)

scoreCount :: [String] -> Int -> [Int]
scoreCount answList questionNumber =
  if (0 == length (answList!!0))
  then []
  else do
    let currentAnswer = (!!0) <$> answList
    let restAnswers = (drop 1) <$> answList
    let answers = ['A','B','C','D','E']
    let maxScore = maximum ((countLetters currentAnswer) <$> answers)
    maxScore : scoreCount restAnswers (questionNumber + 1)

myDot :: [Int] -> [Int] -> Int
myDot x y = sum (zipWith (*) x y)

main = do
  getLine
  dataInts <- getLine
  let array_ = parseLineToInt dataInts
  let sum_ = sum array_
  let max_ = maximum array_
  if ((mod sum_  2 == 0) &&((2 * max_) <= sum_))
  then putStrLn $ "YES"
  else putStrLn $ "NO"

solv :: [Int] -> Bool
solv l = let s = sum l in
             let mx = maximum l in
                 (mod s 2 == 0) && (mx <= (div s 2))

main = do
  l <- getLine
  let n = (read l) :: Int
  inp <- getLine
  let inn = map read $ words inp
  let res = solv inn
  putStrLn $ if res then "YES" else "NO"


Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions:  The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.  No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n).  Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.

A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters.

In a single line print the required string. If there isn't such string, print "-1" (without the quotes).

import Control.Monad
import Control.Applicative
import Control.Arrow

import Data.List
import Data.Maybe

main = do
    [n,k] <- map read . words <$> getLine
    putStrLn $ solve n k

alphabet = "abcdefghijklmnopqrstuvwxyz"

solve :: Int -> Int -> String
solve 1 1 = "a"
solve 1 n = "-1"
solve n 1 = "-1"
solve n 2 = take n (cycle "ab")
solve n k | k > n       = "-1"
          | even (n-k)  = take (n-k) (cycle "ab") ++ take k alphabet
          | otherwise   = take (n-k) (cycle "ab") ++ "ba" ++ take (k-2) (drop 2 alphabet)

import Control.Applicative
import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
showBI :: Int -> B.ByteString
showBI = B.pack . show
readBI :: B.ByteString -> Int
readBI = fst . fromJust . B.readInt

main = B.interact $ B.pack . go . map readBI . B.words
go (n:k:[]) | k == 1 = if n == 1 then "a" else "-1"
            | n >= k = (take (n-k+2) . cycle $ "ab") ++ (take (k-2) ['c'..'z'])
            | otherwise = "-1"

import Control.Applicative
import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
showBI :: Int -> B.ByteString
showBI = B.pack . show
readBI :: B.ByteString -> Int
readBI = fst . fromJust . B.readInt

main = interact $ go . map read . words
go (n:k:[]) | k == 1 = if n == 1 then "a" else "-1"
            | n >= k = (take (n-k+2) . cycle $ "ab") ++ (take (k-2) ['c'..'z'])
            | otherwise = "-1"

import System.IO
import Data.Char(chr)

main :: IO ()
main = interact (handle)

handle :: String -> String
handle str =
   let ints = pair_up $ map (\x -> read x :: Int) $ take 2 $ words str
   in  solve False ints

pair_up :: [Int] -> (Int, Int)
pair_up (x:y:_) = (x, y)
pair_up _ = undefined

solve :: Bool -> (Int, Int) -> String
solve False (l,d)
    | l < d            = "-1"
    | d == 1 && l > 1  = "-1"
    | d == 1 && l == 1 = "a"
    | l == d           = 'a':'b':(make_tail (l-2) (d-2))
    | l == d + 1       = 'a':'b':(make_tail (l-2) (d-2))
    | otherwise        = 'a':'b':(solve True (l-2,d))
solve True (l,d)
    | l == d           = 'a':'b':(make_tail (l-2) (d-2))
    | l == d + 1       = 'a':'b':(make_tail (l-2) (d-2))
    | otherwise        = 'a':'b':(solve True (l-2,d))

make_tail :: Int -> Int -> String
make_tail m n
    | m == n + 1         = 'a':(map chr [99..(99+n-1)])
    | m == n             = map chr [99..(99+n-1)]
    | otherwise          = undefined

main=interact$f.map read.words
f[1,1]="a"
f[n,k]|n<k||k<2="-1"|0<1=take(n-k+2)(cycle"ab")++take(k-2)['c'..]

{-# 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.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
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

import qualified Data.ByteString.Lazy.Builder as BB

import Data.Monoid
import System.IO

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

main = do
  [n, k] <- getInts

  let
    r
      | n < k = Nothing
      | k == 1 = if n == 1 then Just "a" else Nothing
      | otherwise = Just $ (take (n-(k-2)) $ concat $ repeat "ab") ++ take (k-2) ['c'..]

  putStrLn $ case r of
               Nothing -> show (-1)
               Just k -> k

s[1,1]="a"
s[n,1]="-1"
s[n,k]|n<k="-1"
 |otherwise=take n(take i(cycle "ab")++['c'..]) where
  i = n - (k-2)
main=interact$s.map read.words

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

getNums :: (Read a, Num a) => IO [a]
getNums = map read . words <$> getLine

-- | templ

main :: IO ()
main = do
  [n, k] <- getNums
  case () of
    _ | n < k || (k == 1 && n > 1) -> print (-1)
      | even (n-k) -> putStrLn $ concat ["a", concat (replicate ((n-k)`div`2) "ba"), take (k-1) ['b'..]]
      | otherwise -> putStrLn $ concat ["a", concat (replicate ((n-k+1)`div`2) "ba"), take (k-2) ['c'..]]

import Data.Char
f a b | b > a || (b == 1 && a > 1) = "-1"
      | b == 1 && a == 1 = "a"
      | otherwise = (concat $ replicate delta "ab") ++ s' ++ ['c'..maxLet]
        where delta = (a - b + 2) `div` 2
              s' = if odd (a - b) then "a" else ""
              maxLet = chr $ ord 'c' + (b - 3)
main = do
    a:b:_ <- fmap (map (read :: String -> Int) . words) getLine
    putStrLn $ f a b

import Control.Applicative
import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
showBI :: Int -> B.ByteString
showBI = B.pack . show
readBI :: B.ByteString -> Int
readBI = fst . fromJust . B.readInt

main = B.interact $ B.pack . go . map readBI . B.words
go (n:k:[]) | n >= k = (take (n-k+2) . cycle $ "ab") ++ (take (k-2) ['c'..'z'])
            | otherwise = "-1"

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

getNums :: (Read a, Num a) => IO [a]
getNums = map read . words <$> getLine

-- | templ

main :: IO ()
main = do
  [n, k] <- getNums
  case () of
    _ | n < k -> print (-1)
      | even (n-k) -> putStrLn $ concat ["a", concat (replicate ((n-k)`div`2) "ba"), take (k-1) ['b'..]]
      | otherwise -> putStrLn $ concat ["a", concat (replicate ((n-k+1)`div`2) "ba"), take (k-2) ['c'..]]


Let's define the cost of a string $$$s$$$ as the number of index pairs $$$i$$$ and $$$j$$$ ($$$1 \le i < j < |s|$$$) such that $$$s_i = s_j$$$ and $$$s_{i+1} = s_{j+1}$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Among all strings with length $$$n$$$ that contain only the first $$$k$$$ characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.

The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 26$$$).

Print the string $$$s$$$ such that it consists of $$$n$$$ characters, each its character is one of the $$$k$$$ first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings — print any of them.

import Control.Monad
import Data.List
import Text.Printf

readArray :: Read a => IO [a]
readArray = fmap (map read . words) getLine

readInts :: IO [Int]
readInts = readArray

lyndonCut :: Char -> String -> String
lyndonCut m [] = []
lyndonCut m (c:s)
  | c == m = lyndonCut m s
  | otherwise = ((toEnum (fromEnum c + 1)):s)

nextLyndonWord :: Int -> Char -> String -> String
nextLyndonWord n m s =
  reverse $ lyndonCut m $ reverse $ take n $ concat $ repeat s

lyndonWords :: Int -> Char -> [String]
lyndonWords n c =
  takeWhile (not . null) $ iterate (nextLyndonWord n c) "a"

deBruijn :: Int -> Char -> String
deBruijn n =
  concat . filter (\a -> n `mod` length a == 0) . lyndonWords n

solve :: Int -> Int -> String
solve n k =
  take n $ concat $ repeat $ deBruijn 2 $ toEnum $ fromEnum 'a' + k - 1

solveCase :: IO String
solveCase = do
  [n, k] <- readInts
  return $ solve n k

main :: IO ()
main = solveCase >>= putStrLn

--solveCase :: IO String
--solveCase = do
--  (n:x:[]) <- readInts
--  fmap (show . solve x) readInts
--
--main :: IO ()
--main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)

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

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

main :: IO ()
main = do
  [n, k] <- getInts
  let maxChar = toEnum (fromEnum 'a' + k - 1) :: Char
      func _ [] = []
      func ch (x : xs) = x : ch : func ch xs
      s = concat ['a' : func ch [ch..maxChar] | ch <- ['b'..maxChar]] ++ "a"
      t = take n $ 'a' : concat (repeat s)
  C.putStrLn $ C.pack t


There is a board with a grid consisting of n rows and m columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number i and column number j as (i, j).A group of six numbers (a, b, c, d, x0, y0), where 0 ≤ a, b, c, d, is a cross, and there is a set of cells that are assigned to it. Cell (x, y) belongs to this set if at least one of two conditions are fulfilled:  |x0 - x| ≤ a and |y0 - y| ≤ b  |x0 - x| ≤ c and |y0 - y| ≤ d    The picture shows the cross (0, 1, 1, 0, 2, 3) on the grid 3 × 4.  Your task is to find the number of different groups of six numbers, (a, b, c, d, x0, y0) that determine the crosses of an area equal to s, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell (x, y) of the cross 1 ≤ x ≤ n; 1 ≤ y ≤ m holds). The area of the cross is the number of cells it has.Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points.

The input consists of a single line containing three integers n, m and s (1 ≤ n, m ≤ 500, 1 ≤ s ≤ n·m). The integers are separated by a space.

Print a single integer — the number of distinct groups of six integers that denote crosses with area s and that are fully placed on the n × m grid. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the sought groups of six numbers are: (0, 0, 0, 0, 1, 1), (0, 0, 0, 0, 1, 2), (0, 0, 0, 0, 2, 1), (0, 0, 0, 0, 2, 2).In the second sample the sought groups of six numbers are: (0, 1, 1, 0, 2, 2), (0, 1, 1, 0, 2, 3), (1, 0, 0, 1, 2, 2), (1, 0, 0, 1, 2, 3).

import Data.Array

main = do
  [n, m, s] <- fmap (map read . words) getLine
  print $ solve n m s

solve n m s = sum $ rect ++ cross
  where
    a = accumArray (flip (:)) [] (0, n * m) $
      [(i * j, (i, j)) | i <- [1, 3 .. n], j <- [1, 3 .. m]]
    ord x = succ x `div` 2
    count r c = (n + 1 - r) * (m + 1 - c)
    rect = [count r c * (k + k - 1)  | (r, c) <- a!s, let k = ord r * ord c]
    cross = [count r c * 2 |
        u <- [1 .. div n 2],
        v <- [1 .. div m 2],
        let t = s + 4 * u * v,
        t <= n * m,
        (r, c) <- a!t,
        2 * u < r && 2 * v < c]


Ezzat has an array of $$$n$$$ integers (maybe negative). He wants to split it into two non-empty subsequences $$$a$$$ and $$$b$$$, such that every element from the array belongs to exactly one subsequence, and the value of $$$f(a) + f(b)$$$ is the maximum possible value, where $$$f(x)$$$ is the average of the subsequence $$$x$$$. A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of $$$[1,5,6]$$$ is $$$(1+5+6)/3 = 12/3 = 4$$$, so $$$f([1,5,6]) = 4$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$)— the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test case, print a single value — the maximum value that Ezzat can achieve. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. 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^{-6}$$$.

{-# LANGUAGE Strict #-}
{-# LANGUAGE LambdaCase #-}
import Control.Applicative (liftA2)
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)
import Numeric (showFFloat)

main :: IO ()
main = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))

testCase :: Scanner String
testCase = do
  n <- int
  xs <- n >< int
  let s = sum $ map fromIntegral xs
  let m = fromIntegral $ maximum xs
  let n' = fromIntegral n - 1
  let v = m + (s - m) / n'
  return $ showFFloat (Just 10) v ""

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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


Suppose you are living with two cats: A and B. There are $$$n$$$ napping spots where both cats usually sleep.Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:   Cat A changes its napping place in order: $$$n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots$$$ In other words, at the first hour it's on the spot $$$n$$$ and then goes in decreasing order cyclically;  Cat B changes its napping place in order: $$$1, 2, 3, \dots, n - 1, n, 1, 2, \dots$$$ In other words, at the first hour it's on the spot $$$1$$$ and then goes in increasing order cyclically. The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $$$x$$$ then the A takes this place and B moves to the next place in its order (if $$$x < n$$$ then to $$$x + 1$$$, but if $$$x = n$$$ then to $$$1$$$). Cat B follows his order, so it won't return to the skipped spot $$$x$$$ after A frees it, but will move to the spot $$$x + 2$$$ and so on.Calculate, where cat B will be at hour $$$k$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$) — the number of spots and hour $$$k$$$.

For each test case, print one integer — the index of the spot where cat B will sleep at hour $$$k$$$.

NoteIn the first and second test cases $$$n = 2$$$, so:   at the $$$1$$$-st hour, A is on spot $$$2$$$ and B is on $$$1$$$;  at the $$$2$$$-nd hour, A moves to spot $$$1$$$ and B — to $$$2$$$.  If $$$n = 3$$$ then:   at the $$$1$$$-st hour, A is on spot $$$3$$$ and B is on $$$1$$$;  at the $$$2$$$-nd hour, A moves to spot $$$2$$$; B'd like to move from $$$1$$$ to $$$2$$$, but this spot is occupied, so it moves to $$$3$$$;  at the $$$3$$$-rd hour, A moves to spot $$$1$$$; B also would like to move from $$$3$$$ to $$$1$$$, but this spot is occupied, so it moves to $$$2$$$. In the sixth test case:   A's spots at each hour are $$$[5, 4, 3, 2, 1]$$$;  B's spots at each hour are $$$[1, 2, 4, 5, 2]$$$.

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
    [n, k] <- getInts
    let
      result
        | even n = (k - 1) `mod` n + 1
        | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)
        where
        m = n - 1
        p = k - 1
      solve s p
        | p < n `div` 2 = (s + p - 1) `mod` n + 1
        | otherwise = (s + p) `mod` n + 1
    C.putStrLn $ C.pack $ show result

main = do
    getLine
    interact $ unlines . map (show . solve' . words) . lines

solve' [x, y] = solve ((read x) :: Integer) ((read y) :: Integer)

solve n k = if (mod n 2) == 0
                then let a = mod k n in if a == 0 then n else a
                else soleven n k

soleven n k = let x = mod (apos + r) n in if x == 0 then n else x
  where
    t = div (n - 1) 2
    m = div (k - 1) t
    r = k - 1 - m * t
    apos = (n + 1) - let a = (mod (m * t) n) in if a == 0 then n else a

main = interact $ unlines.map show.f.map read.tail.words

f [] = []
f (n:k_:xs) =
    let k = k_ - 1; fl = n `div` 2
    in ((k + (n `mod` 2) * k `div` fl) `mod` n + 1) : f xs

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
module Main where

import           Control.Monad                  ( replicateM_ )

catCycle :: Int -> Int -> Int
catCycle n (pred -> k) | even n    = (k `mod` n) + 1
                       | otherwise = ((k + step) `mod` n) + 1
  where step = k `div` ((n - 1) `div` 2)

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, k] <- fmap read . words <$> getLine
    print $ catCycle n k

{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,
    ConstraintKinds, BangPatterns #-}

import Control.Monad
import Control.Monad.State
import Data.Array
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

runHopper :: Hopper r a -> [r] -> (a, [r])
runHopper = runState

evalHopper :: Hopper r a -> [r] -> a
evalHopper = evalState

runHopperT :: HopperT r m a -> [r] -> m (a, [r])
runHopperT = runStateT

evalHopperT :: Monad m => HopperT r m a -> [r] -> m a
evalHopperT = evalStateT

type MonadHopper r m = MonadState [r] m

pop :: MonadHopper r m => m (Maybe r)
pop = state f
  where
    f :: [r] -> (Maybe r, [r])
    f [] = (Nothing, [])
    f (q:qs) = (Just q, qs)

popJust :: MonadHopper r m => m r
popJust = fromJust <$> pop

------

popInt :: MonadHopper B.ByteString m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

popInts :: MonadHopper B.ByteString m => m [Int]
popInts = map (fst . fromJust . B.readInt) . B.words <$> popJust

popInteger :: MonadHopper B.ByteString m => m Integer
popInteger = fst . fromJust . B.readInteger <$> popJust

popIntegers :: MonadHopper B.ByteString m => m [Integer]
popIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust

------

dropCR :: B.ByteString -> B.ByteString
dropCR s | not (B.null s) && B.last s == '\r' = B.init s
         | otherwise = s

bshow :: Show a => a -> B.ByteString
bshow = B.pack . show

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map dropCR . B.lines

------

run :: Hopper B.ByteString B.ByteString
run = do
  t <- popInt
  B.unlines <$> replicateM t run1

run1 = do
  ~[n, k] <- popIntegers
  return $ bshow (solve n (k - 1))

solve !n !k
  | n `rem` 2 == 0 = k `rem` n + 1
  | otherwise =
    let c = n `quot` 2
        k' = k `rem` (n * c)
        (p, q) = k' `quotRem` c in
      (p * (c + 1) + q) `rem` n + 1

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

type SIO = StateT P.ByteString IO

solve :: Int -> Int -> Int
solve n k
  | even n  = mod k n
  | odd n  = let
      per = div n 2
      (x, y) = divMod (k-1) per
      totSteps = x * (per + 1) + y + 1
      in  mod totSteps n

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, k] <- readInts
    let
      ans0 = solve n k
      ans = if  ans0 == 0  then  n  else  ans0
    putInts [ans]

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder

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
    [n, k] <- getInts
    let
      result
        | even n = (k - 1) `mod` n + 1
        | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)
        where
        m = n - 1
        p = k - 1
      solve s p
        | p < n `div` 2 = s + p
        | otherwise = (s + p) `mod` n + 1
    C.putStrLn $ C.pack $ show result

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
    [n, k] <- getInts
    let
      result
        | even n = (k - 1) `mod` n + 1
        | otherwise = solve (1 + (p `div` m) `mod` n) (p `mod` m)
        where
        m = n - 1
        p = k - 1
      solve s p
        | p < n `div` 2 = s + p
        | otherwise = s + 1 + p
    C.putStrLn $ C.pack $ show result

main = do
    getLine
    interact $ unlines . map (show . solve' . words) . lines

solve' [x, y] = solve ((read x) :: Integer) ((read y) :: Integer)

solve n k = if (mod n 2) == 0
                then let a = mod k n in if a == 0 then n else a
                else soleven n k

soleven n k = apos + r
  where
    t = div (n - 1) 2
    m = div (k - 1) t
    r = k - 1 - m * t
    apos = (n + 1) - let a = (mod (m * t) n) in if a == 0 then n else a