{-# LANGUAGE BangPatterns, Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.List
import Data.Int

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

solve :: [Int] -> Builder
solve (n:a) = int64Dec res
  where
    res :: Int64
    res = sum $ map fromIntegral $ scanr1 (\k acc -> max 0 $ min k (pred acc)) $ take n a

main :: IO ()
main = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents

main = interact $ show . i . reverse . map read . words . last . lines

i []   = choco 0 []
i (x:[]) = choco x []
i (x:xs) = choco x xs

choco :: Integer -> [Integer] -> Integer
choco a [] = a
choco a (x:xs)
  | x >= a    = a + choco (max (a-1) 0) xs
  | otherwise = a + choco x xs

main = interact $ show . choco . reverse . map read . words . last . lines

choco :: [Integer] -> Integer
choco [] = 0
choco (a:[]) = a
choco (a:x:xs)
  | x >= a    = a + choco ((max (a-1) 0):xs)
  | otherwise = a + choco (x:xs)

module Main where
import qualified Data.ByteString.Char8 as C
import Data.List

main = do
    C.getLine
    as <- reverse . map ((read :: String -> Integer ). C.unpack ) . C.words <$> C.getLine
    let zero x = if x < 0 then 0 else x
    print $ sum $  foldl' (\acc@(h:_) x -> ((if x >= h then zero $ h-1 else x):acc)) [head as] $ tail as

main :: IO ()
main = interact $ show . solve . fmap read . tail . words

solve :: [Integer] -> Integer
solve = sum . scanr1 greedy

greedy :: Integer -> Integer -> Integer
greedy _ 0 = 0
greedy l r | l >= r = r - 1
           | otherwise = l

module Main where
import qualified Data.ByteString.Char8 as C
import Data.List

main = do
    C.getLine
    as <- reverse . map ((read :: String -> Int) . C.unpack ) . C.words <$> C.getLine
    let zero x = if x < 0 then 0 else x
    print $ sum $  foldl' (\acc@(h:_) x -> ((if x >= h then zero $ h-1 else x):acc)) [head as] $ tail as


{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Strict
import Data.Array
import Data.List
import Data.Maybe
import qualified Data.IntSet as S
import qualified Data.IntMap as M

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  m <- poi
  s <- poi
  t <- poi
  g <- replicateM m $ liftM2 (,) poi poi
  return $ show $ solve n s t g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n s t (accumArray (flip S.insert) S.empty (1, n) . concatMap (\(a, b) -> [(a, b), (b, a)]) -> g) | ds <- bfs s g, dt <- bfs t g, Just c <- M.lookup t ds = sum [1 :: Int | (u, v) <- pairs [1..n], S.notMember u (g!v), fromMaybe False $ liftM4 (\su sv ut vt -> su + vt + 1 >= c && sv + ut + 1 >= c) (M.lookup u ds) (M.lookup v ds) (M.lookup u dt) (M.lookup v dt)]

bfs s = go 0 [s] M.empty
  where
  go _ [] m _ = m
  go d us m g | m' <- foldl' (flip (`M.insert` d)) m us  = (\us' -> go (d + 1) us' m' g) $ filter (not . flip M.member m') $ concatMap (S.toList . (g!)) us

pairs xs = [(a, b) | (a:bs) <- tails xs, b <- bs]

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE ViewPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Strict
import Data.Array
import Data.List
import Data.Maybe
import qualified Data.IntMap as M

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  m <- poi
  s <- poi
  t <- poi
  g <- replicateM m $ liftM2 (,) poi poi
  return $ show $ solve n m s t g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n m s t (accumArray (flip (:)) [] (1, n) . concatMap (\(a, b) -> [(a, b), (b, a)]) -> g) | ds <- bfs s g, dt <- bfs t g, Just c <- M.lookup t ds = sum [1 :: Int | (u, v) <- pairs [1..n], fromMaybe False $ liftM4 (\su sv ut vt -> su + vt + 1 >= c && sv + ut + 1 >= c) (M.lookup u ds) (M.lookup v ds) (M.lookup u dt) (M.lookup v dt)] - m

bfs s = go 0 [s] M.empty
  where
  go _ [] m _ = m
  go d us m g | m' <- foldl' (flip (`M.insert` d)) m us  = (\us' -> go (d + 1) us' m' g) $ filter (not . flip M.member m') $ concatMap (g!) us

pairs xs = [(a, b) | (a:bs) <- tails xs, b <- bs]

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Maybe(fromMaybe)

type Cost = Int
type Vertex = Int
type Edge = ((Vertex, Vertex), Cost)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) . S.fromList $ zip roads [1, 1..]

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = dijkstra n s edge
                             gDist = dijkstra n g edge
                             originalTime = sDist ! g
                         in
                          do
                           l <- [1..n - 1]
                           r <- [l + 1..n]
                           guard $ ((l, r), 1) `S.notMember` edge
                           let route1 = sDist ! l + gDist ! r + 1
                               route2 = sDist ! r + gDist ! l + 1
                           guard $ min route1 route2 >= originalTime
                           return ((l, r), 1)

dijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost
dijkstra n s edge = let connect = foldl' (\ cMap ((a, b), c) -> insertList a b c cMap) (M.fromList [(x, []) | x <- [1..n]]) $ S.toList edge
                        costArray = runSTUArray $ do
                                                   mArray <- newArray (1, n) maxBound :: ST s (STUArray s Vertex Cost)
                                                   let reachable = fromMaybe (error "key error") $ M.lookup s connect
                                                   forM_ reachable $ uncurry (writeArray mArray)
                                                   return mArray
                        costSet = S.delete (maxBound::Int, s) . S.fromList . map (\ (a, b) -> (b, a)) $ assocs costArray
                     in runSTUArray $ do
                                       mArray <- thaw costArray
                                       loop s connect costSet mArray
                                       return mArray

loop:: Vertex -> M.Map Vertex [(Vertex, Cost)] -> S.Set (Cost, Vertex) -> STUArray s Vertex Cost -> ST s ()
loop s connect costSet costArray = if S.null costSet then writeArray costArray s 0
                                                     else do
                                                           let (minCost, minVertex) = S.findMin costSet
                                                               reachable = fromMaybe (error "key error") $ M.lookup minVertex connect
                                                           newCostSet <- foldM (\ cSet (v, c) -> do
                                                                                let newCost = minCost + c
                                                                                oldCost <- readArray costArray v
                                                                                if newCost < oldCost then do
                                                                                writeArray costArray v newCost
                                                                                return $ S.insert (newCost, v) $ S.delete (oldCost, v) cSet
                                                                                else return cSet) (S.deleteMin costSet) reachable
                                                           loop s connect newCostSet costArray

insertList:: Vertex -> Vertex -> Cost -> M.Map Vertex [(Vertex, Cost)] -> M.Map Vertex [(Vertex, Cost)]
insertList a b c = M.update (\ x -> Just $ (a, c):x) b . M.update (\x -> Just $ (b, c):x) a

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

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Maybe(fromMaybe)

type Cost = Int
type Vertex = Int
type Edge = ((Vertex, Vertex), Cost)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) . S.fromList $ zip roads [1, 1..]

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = dijkstra n s edge
                             gDist = dijkstra n g edge
                             originalTime = sDist ! g
                         in
                          do
                           l <- [1..n - 1]
                           r <- [l + 1..n]
                           guard $ ((l, r), 1) `S.notMember` edge
                           let route1 = sDist ! l + gDist ! r + 1
                               route2 = sDist ! r + gDist ! l + 1
                           guard $ min route1 route2 >= originalTime
                           return ((l, r), 1)

dijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost
dijkstra n s edge = let connect = foldl' (\ cMap ((a, b), c) -> insertMap a b c cMap) (M.fromList [(x, S.empty) | x <- [1..n]]) $ S.toList edge
                        costArray = runSTUArray $ do
                                                   mArray <- newArray (1, n) maxBound :: ST s (STUArray s Vertex Cost)
                                                   let reachable = S.toList . fromMaybe (error "key error") $ M.lookup s connect
                                                   forM_ reachable $ uncurry (writeArray mArray)
                                                   return mArray
                        costSet = S.delete (maxBound::Int, s) . S.fromList . map (\ (a, b) -> (b, a)) $ assocs costArray
                     in runSTUArray $ do
                                       mArray <- thaw costArray
                                       loop s connect costSet mArray
                                       return mArray

loop:: Vertex -> M.Map Vertex (S.Set (Vertex, Cost)) -> S.Set (Cost, Vertex) -> STUArray s Vertex Cost -> ST s ()
loop s connect costSet costArray = if S.null costSet then writeArray costArray s 0
                                                     else do
                                                           let (minCost, minVertex) = S.findMin costSet
                                                               reachable = S.toList $ fromMaybe (error "key error") $ M.lookup minVertex connect
                                                           newCostSet <- foldM (\ cSet (v, c) -> do
                                                                                let newCost = minCost + c
                                                                                oldCost <- readArray costArray v
                                                                                if newCost < oldCost then do
                                                                                writeArray costArray v newCost
                                                                                return $ S.insert (newCost, v) $ S.delete (oldCost, v) cSet
                                                                                else return cSet) (S.deleteMin costSet) reachable
                                                           loop s connect newCostSet costArray

insertMap:: Vertex -> Vertex -> Cost -> M.Map Vertex (S.Set (Vertex, Cost)) -> M.Map Vertex (S.Set (Vertex, Cost))
insertMap a b c = M.update (\ x -> Just $ S.insert (a, c) x) b . M.update (\x -> Just $ S.insert (b, c) x) a

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

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Maybe(fromMaybe)

type Cost = Int
type Vertex = Int
type Edge = (Vertex, Vertex)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) $ S.fromList roads

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = bfs n s edge
                             gDist = bfs n g edge
                             originalTime = sDist ! g
                         in do
                             start <- [1..n - 1]
                             end <- [start + 1..n]
                             guard $ (start, end) `S.notMember` edge
                             let route1 = sDist ! start + gDist ! end + 1
                                 route2 = sDist ! end + gDist ! start + 1
                             guard $ route1 >= originalTime && route2 >= originalTime
                             return (start, end)

bfs:: Int -> Vertex -> S.Set Edge -> UArray Vertex Cost
bfs n s edge = let connect = foldl' (\ cMap (a, b) -> update a b cMap) (M.fromList [(x, S.empty) | x <- [1..n]]) $ S.toList edge
                   queue = (s, 0):walk 1 queue connect (S.fromList [s])
               in array (1, n) queue

walk:: Int -> [(Vertex, Cost)] -> M.Map Vertex (S.Set Vertex) -> S.Set Vertex -> [(Vertex, Cost)]
walk 0 _ _ used = []
walk n ((v, c):rest) connect used = let reachable = fromMaybe (error "key error") $ M.lookup v connect
                                        unreached = S.toList $ S.filter (`S.notMember` used) reachable
                                        add = zip unreached [c + 1, c + 1..]
                                        newUsed = foldl' (flip S.insert) used unreached
                                    in add ++ walk (n + length add - 1) rest connect newUsed

update:: Vertex -> Vertex -> M.Map Vertex (S.Set Vertex) -> M.Map Vertex (S.Set Vertex)
update a b = M.update (\ x -> Just $ S.insert a x) b . M.update (\x -> Just $ S.insert b x) a

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

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.Set as S
import qualified Data.Map as M

type Cost = Int
type Vertex = Int
type Edge = ((Vertex, Vertex), Cost)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) . S.fromList $ zip roads [1,1..]

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = dijkstra n s edge
                             gDist = dijkstra n g edge
                             originalTime = sDist ! g
                         in do
                             start <- [1..n - 1]
                             end <- [start + 1..n]
                             guard $ ((start, end), 1) `S.notMember` edge
                             let route1 = sDist ! start + gDist ! end + 1
                                 route2 = sDist ! end + gDist ! start + 1
                             guard $ route1 >= originalTime && route2 >= originalTime
                             return ((start, end), 1)

dijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost
dijkstra n s edge = let initialArray = runSTUArray $ do
                                                      mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)
                                                      let reachable = S.toList . omit s $ S.filter (\ ((a, b), c) -> a == s || b == s) edge
                                                      forM_ reachable $ uncurry (writeArray mArray)
                                                      return mArray
                        initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\ (a, b) -> (b, a)) $ assocs initialArray
                        initialMap = M.delete s . M.fromList $ assocs initialArray
                    in array (1, n) . M.toList $ recursive s edge initialSet initialMap M.empty

recursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost
recursive s edge costSet costMap distMap
 | S.null costSet = M.insert s 0 distMap
 | otherwise = let (minCost, minVertex) = S.findMin costSet
                   newDistMap = M.insert minVertex minCost distMap
                   neighbors = S.toList . omit minVertex $ S.filter (\ ((a, b), c) -> a == minVertex || b == minVertex) edge
                   (newCostSet, newCostMap) = foldl' (\ (cSet, cMap) (a, c) -> case M.lookup a cMap of
                                                                                Just oldCost -> if minCost + c < oldCost
                                                                                then (S.insert (minCost + c, a) $ S.delete (oldCost, a) cSet, M.update (\_ -> Just $ minCost + c) a cMap)
                                                                                else (cSet, cMap)
                                                                                Nothing -> (cSet, cMap))
                                               (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors
               in recursive s edge newCostSet newCostMap newDistMap

omit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)
omit x = S.map (\ ((a, b), c) -> if a == x then (b, c) else (a, c))

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

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.Set as S
import qualified Data.Map as M
import Data.Maybe(fromMaybe)

type Cost = Int
type Vertex = Int
type Edge = (Vertex, Vertex)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) $ S.fromList roads

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = bfs n s edge
                             gDist = bfs n g edge
                             originalTime = sDist ! g
                         in do
                             start <- [1..n - 1]
                             end <- [start + 1..n]
                             guard $ (start, end) `S.notMember` edge
                             let route1 = sDist ! start + gDist ! end + 1
                                 route2 = sDist ! end + gDist ! start + 1
                             guard $ route1 >= originalTime && route2 >= originalTime
                             return (start, end)

bfs:: Int -> Vertex -> S.Set Edge -> UArray Vertex Cost
bfs n s edge = let connect = foldl' (\ cMap (a, b) -> update a b cMap) (M.fromList [(x, S.empty) | x <- [1..n]]) $ S.toList edge
                   queue = (s, 0):walk n queue connect (S.fromList [s])
               in array (1, n) queue

walk:: Int -> [(Vertex, Cost)] -> M.Map Vertex (S.Set Vertex) -> S.Set Vertex -> [(Vertex, Cost)]
walk n _ _ used
 | S.size used == n = []
walk n ((v, c):rest) connect used = let reachable = fromMaybe (error "key error") $ M.lookup v connect
                                        unreached = S.toList $ S.filter (\x -> x `S.notMember` used) reachable
                                        add = zip unreached [c + 1, c + 1..]
                                        newUsed = foldl' (\ set x -> S.insert x set) used unreached
                                    in if null add then walk n rest connect newUsed
                                                   else add ++ walk n rest connect newUsed

update:: Vertex -> Vertex -> M.Map Vertex (S.Set Vertex) -> M.Map Vertex (S.Set Vertex)
update a b = M.update (\ x -> Just $ S.insert a x) b . M.update (\x -> Just $ S.insert b x) a

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

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.Set as S
import qualified Data.Map as M

type Cost = Int
type Vertex = Int
type Edge = ((Vertex, Vertex), Cost)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . sort . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) . S.fromList $ zip roads [1,1..]

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = dijkstra n s edge
                             gDist = dijkstra n g edge
                             originalTime = sDist ! g
                         in do
                             start <- [1..n - 1]
                             end <- [start + 1..n]
                             guard $ ((start, end), 1) `S.notMember` edge
                             let route1 = sDist ! start + gDist ! end + 1
                                 route2 = sDist ! end + gDist ! start + 1
                             guard $ route1 >= originalTime && route2 >= originalTime
                             return ((start, end), 1)

dijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost
dijkstra n s edge = let initialArray = runSTUArray $ do
                                                      mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)
                                                      let reachable = S.toList . omit s $ S.filter (\ ((a, b), c) -> a == s || b == s) edge
                                                      forM_ reachable $ uncurry (writeArray mArray)
                                                      return mArray
                        initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\ (a, b) -> (b, a)) $ assocs initialArray
                        initialMap = M.delete s . M.fromList $ assocs initialArray
                    in array (1, n) . M.toList $ recursive s edge initialSet initialMap M.empty

recursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost
recursive s edge costSet costMap distMap
 | S.null costSet = M.insert s 0 distMap
 | otherwise = let (minCost, minVertex) = S.findMin costSet
                   newDistMap = M.insert minVertex minCost distMap
                   neighbors = S.toList . omit minVertex $ S.filter (\ ((a, b), c) -> a == minVertex || b == minVertex) edge
                   (newCostSet, newCostMap) = foldl' (\ (cSet, cMap) (a, c) -> case M.lookup a cMap of
                                                                                Just cost -> if minCost + c < cost then update a (minCost + c) cSet cMap else (cSet, cMap)
                                                                                Nothing -> (cSet, cMap))
                                               (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors
               in recursive s edge newCostSet newCostMap newDistMap

update::Vertex -> Cost -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> (S.Set (Cost, Vertex), M.Map Vertex Cost)
update a newCost costSet costMap = case M.lookup a costMap of
                                    Just oldCost -> (S.insert (newCost, a) $ S.delete (oldCost, a) costSet, M.update (\_ -> Just newCost) a costMap)
                                    Nothing -> error "key doesn't exist"

omit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)
omit x = S.map (\ ((a, b), c) -> if a == x then (b, c) else (a, c))

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

import Control.Monad
import Control.Applicative
import Data.List
import Data.Maybe
import Data.Function (fix)
import Data.Array (Array, array, (!))
import qualified Data.Sequence as S
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

getInts :: IO [Int]
getInts = (map parseInt . BS8.words) <$> BS.getLine
    where parseInt = fst . fromJust . BS8.readInt

bfsDo :: [(Int, Int)] -> Int -> Int -> S.Seq Int
bfsDo edges s n = bfs edges (S.singleton s) (S.update s 0 $ S.fromList (replicate n (-1)))

a !. b = a `S.index` b

bfs :: [(Int, Int)] -> S.Seq Int -> S.Seq Int -> S.Seq Int
bfs edges q d
    | S.null q = d
    | otherwise = let now = q !. 0
                      nowDist = d !. now
                      nexts = map snd $ filter (\(a,b) -> a == now && d !. b == -1) edges in
                      bfs edges ((S.drop 1 q) S.>< (S.fromList nexts)) (foldl (\ad n -> S.update n (nowDist +1) ad) d nexts)

solve :: [(Int, Int)] -> Int -> Int -> Int -> Int
solve edges n s t = dcount - length edges `div` 2
    where sdist = bfsDo edges s n
          tdist = bfsDo edges t n
          st = sdist !. t
          minDist x y = min (sdist !. x + 1 + tdist !. y) (sdist !. y + 1 + tdist !. x)
          dcount = length $ filter (\(x,y) -> minDist x y >= st) $ [(x,y) | x <- [0..n-1], y <- [x+1..n-1]]

main :: IO ()
main = do
    [n,m,s,t] <- getInts
    edges <- concat <$> replicateM m (getInts >>= (\[a,b] -> pure [(a-1,b-1),(b-1,a-1)]))
    print $ solve edges n (s-1) (t-1)

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Maybe(fromMaybe)
import qualified Data.Set as S
import qualified Data.Map as M

type Cost = Int
type Vertex = Int
type Edge = ((Vertex, Vertex), Cost)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) . S.fromList $ zip roads [1, 1..]

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = dijkstra n s edge
                             gDist = dijkstra n g edge
                             originalTime = fromMaybe (error "unreachable") $ M.lookup g sDist
                         in do
                             start <- [1..n - 1]
                             end <- [start + 1..n]
                             guard $ ((start, end), 1) `S.notMember` edge
                             let route1 = fromMaybe (error "unreachable") (M.lookup start sDist) + fromMaybe (error "unreachable") (M.lookup end gDist) + 1
                                 route2 = fromMaybe (error "unreachable") (M.lookup end sDist) + fromMaybe (error "unreachable") (M.lookup start gDist) + 1
                             guard $ route1 >= originalTime && route2 >= originalTime
                             return ((start, end), 1)

dijkstra::Int -> Vertex -> S.Set Edge -> M.Map Vertex Cost
dijkstra n s edge = let initialArray = runSTUArray $ do
                                                      mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)
                                                      let reachable = S.toList . omit s $ S.filter (\ ((a, b), c) -> a == s || b == s) edge
                                                      forM_ reachable $ uncurry (writeArray mArray)
                                                      return mArray
                        initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\ (a, b) -> (b, a)) $ assocs initialArray
                        initialMap = M.fromList $ assocs initialArray
                    in recursive s edge initialSet initialMap M.empty

recursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost
recursive s edge costSet costMap distMap
 | S.null costSet = M.insert s 0 distMap
 | otherwise = let (minCost, minVertex) = S.findMin costSet
                   newDistMap = M.insert minVertex minCost distMap
                   neighbors = S.toList . omit minVertex $ S.filter (\ ((a, b), c) -> a == minVertex || b == minVertex) edge
                   (newCostSet, newCostMap) = foldl' (\ (cSet, cMap) (a, c) -> case M.lookup a cMap of
                                                                                Just cost -> if minCost + c < cost then update a (minCost + c) cSet cMap else (cSet, cMap)
                                                                                Nothing -> (cSet, cMap))
                                               (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors
               in recursive s edge newCostSet newCostMap newDistMap

update::Vertex -> Cost -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> (S.Set (Cost, Vertex), M.Map Vertex Cost)
update a c costSet costMap = case M.lookup a costMap of
                              Just oldCost -> (S.insert (c, a) $ S.delete (oldCost, a) costSet, M.update (\_ -> Just c) a costMap)
                              Nothing -> error "key doesn't exist"

omit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)
omit x = S.map (\ ((a, b), c) -> if a == x then (b, c) else (a, c))

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

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Maybe(fromMaybe)
import qualified Data.Set as S
import qualified Data.Map as M

type Cost = Int
type Vertex = Int
type Edge = ((Vertex, Vertex), Cost)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) . S.fromList $ zip roads [1, 1..]

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = dijkstra n s edge
                             gDist = dijkstra n g edge
                             originalTime = sDist ! g
                         in do
                             start <- [1..n - 1]
                             end <- [start + 1..n]
                             guard $ ((start, end), 1) `S.notMember` edge
                             let route1 = sDist ! start + gDist ! end + 1
                                 route2 = sDist ! end + gDist ! start + 1
                             guard $ route1 >= originalTime && route2 >= originalTime
                             return ((start, end), 1)

dijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost
dijkstra n s edge = let initialArray = runSTUArray $ do
                                                      mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)
                                                      let reachable = S.toList . omit s $ S.filter (\ ((a, b), c) -> a == s || b == s) edge
                                                      forM_ reachable $ uncurry (writeArray mArray)
                                                      return mArray
                        initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\ (a, b) -> (b, a)) $ assocs initialArray
                        initialMap = M.fromList $ assocs initialArray
                    in array (1, n) . M.toList $ recursive s edge initialSet initialMap M.empty

recursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost
recursive s edge costSet costMap distMap
 | S.null costSet = M.insert s 0 distMap
 | otherwise = let (minCost, minVertex) = S.findMin costSet
                   newDistMap = M.insert minVertex minCost distMap
                   neighbors = S.toList . omit minVertex $ S.filter (\ ((a, b), c) -> a == minVertex || b == minVertex) edge
                   (newCostSet, newCostMap) = foldl' (\ (cSet, cMap) (a, c) -> case M.lookup a cMap of
                                                                                Just cost -> if minCost + c < cost then update a (minCost + c) cSet cMap else (cSet, cMap)
                                                                                Nothing -> (cSet, cMap))
                                               (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors
               in recursive s edge newCostSet newCostMap newDistMap

update::Vertex -> Cost -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> (S.Set (Cost, Vertex), M.Map Vertex Cost)
update a c costSet costMap = case M.lookup a costMap of
                              Just oldCost -> (S.insert (c, a) $ S.delete (oldCost, a) costSet, M.update (\_ -> Just c) a costMap)
                              Nothing -> error "key doesn't exist"

omit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)
omit x = S.map (\ ((a, b), c) -> if a == x then (b, c) else (a, c))

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

module Main where

import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.Set as S
import qualified Data.Map as M

type Cost = Int
type Vertex = Int
type Edge = ((Vertex, Vertex), Cost)

main = do
 [n, m, s, t] <- map (read:: String -> Int) . words <$> getLine
 roads <- map (tuple . map (read:: String -> Int) . words) . lines <$> getContents
 print . length . possible n (s, t) . S.fromList $ zip roads [1,1..]

possible:: Int -> (Vertex, Vertex) -> S.Set Edge -> [Edge]
possible n (s, g) edge = let sDist = dijkstra n s edge
                             gDist = dijkstra n g edge
                             originalTime = sDist ! g
                         in do
                             start <- [1..n - 1]
                             end <- [start + 1..n]
                             guard $ ((start, end), 1) `S.notMember` edge
                             let route1 = sDist ! start + gDist ! end + 1
                                 route2 = sDist ! end + gDist ! start + 1
                             guard $ route1 >= originalTime && route2 >= originalTime
                             return ((start, end), 1)

dijkstra::Int -> Vertex -> S.Set Edge -> UArray Vertex Cost
dijkstra n s edge = let initialArray = runSTUArray $ do
                                                      mArray <- newArray (1, n) maxBound :: ST s (STUArray s Int Int)
                                                      let reachable = S.toList . omit s $ S.filter (\ ((a, b), c) -> a == s || b == s) edge
                                                      forM_ reachable $ uncurry (writeArray mArray)
                                                      return mArray
                        initialSet = S.delete (maxBound::Int, s) . S.fromList . map (\ (a, b) -> (b, a)) $ assocs initialArray
                        initialMap = M.delete s . M.fromList $ assocs initialArray
                    in array (1, n) . M.toList $ recursive s edge initialSet initialMap M.empty

recursive::Vertex -> S.Set Edge -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> M.Map Vertex Cost -> M.Map Vertex Cost
recursive s edge costSet costMap distMap
 | S.null costSet = M.insert s 0 distMap
 | otherwise = let (minCost, minVertex) = S.findMin costSet
                   newDistMap = M.insert minVertex minCost distMap
                   neighbors = S.toList . omit minVertex $ S.filter (\ ((a, b), c) -> a == minVertex || b == minVertex) edge
                   (newCostSet, newCostMap) = foldl' (\ (cSet, cMap) (a, c) -> case M.lookup a cMap of
                                                                                Just cost -> if minCost + c < cost then update a (minCost + c) cSet cMap else (cSet, cMap)
                                                                                Nothing -> (cSet, cMap))
                                               (S.delete (minCost, minVertex) costSet, M.delete minVertex costMap) neighbors
               in if minCost == (maxBound :: Int) then error "wrong" else recursive s edge newCostSet newCostMap newDistMap

update::Vertex -> Cost -> S.Set (Cost, Vertex) -> M.Map Vertex Cost -> (S.Set (Cost, Vertex), M.Map Vertex Cost)
update a newCost costSet costMap = case M.lookup a costMap of
                                    Just oldCost -> (S.insert (newCost, a) $ S.delete (oldCost, a) costSet, M.update (\_ -> Just newCost) a costMap)
                                    Nothing -> error "key doesn't exist"

omit::Vertex -> S.Set Edge -> S.Set (Vertex, Cost)
omit x = S.map (\ ((a, b), c) -> if a == x then (b, c) else (a, c))

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


main :: IO ()
main = do
    s <- getLine
    let a = map read $ tail $ words s :: [Integer]
    print $ sum $ zipWith (*) a [1..]

main = do getLine >>= print . sum . zipWith (*) [1..] . map read . tail . words

main :: IO ()
main = do
    s <- getLine
    let a = map read $ tail $ words s :: [Integer]
    print $ sum $ map (uncurry (*)) $ zip a [1..]

main :: IO ()
main = do
    s <- getLine
    let a = map read $ tail $ words s :: [Integer]
    print $ sum $ map (\x -> fst x * snd x) $ zip a [1..]

import System.IO
main = do
    s <- getLine
    putStrLn $ show $ sum $ zipWith (*) [1..] $ map read $ tail $ words $ s

main = do getLine >>= print . sum . map ((^2) . read) . tail . words


{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray hiding ((!))
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

getWords  = words <$> getLine :: IO [String]
getInts   = map read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()

---- Answer Code Section ----

factor :: Int -> [Int]
factor n = nub $ concatMap (factor' n) [1..m] where
    m = ceiling (sqrt $ fromIntegral n)
    factor' n i = if n `mod` i == 0 then [i, n `div` i] else []

-- Arithmetic sum
sumSeq n d = n * (2 + (n-1) * d) `div` 2

process :: Int -> [Integer]
process n = map (\f -> sumSeq f (n' `div` f)) factors where
    n' = toInteger n
    factors = map toInteger (sort $ factor n)

main = do
    n <- getInt
    putStrLn $ unwords $ map show $ process n

{-# LANGUAGE BangPatterns #-}
import System.IO
import Control.Applicative
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import Data.ByteString.Lazy.Builder
import Data.ByteString.Lazy.Builder.ASCII
import qualified Data.Map as Map
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]
construct reader str
    | BS.null str = []
    | isSpace (BS8.head str) = construct reader (BS8.tail str)
    | otherwise = let Just (i, other) = reader str in i : construct reader other

getInts :: IO [Int]
getInts = construct BS8.readInt <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = construct BS8.readInteger <$> BS.getLine

printInts :: [Integer] -> IO ()
printInts = putStrLn . intercalate " " . map show

solve n = map toSum $ concat [factors n, factors2 n]
    where cand n = takeWhile (\i -> i * i <= n) [1..]
          factors n = filter (\k -> n `mod` k == 0) $ cand n
          factors2 = map (\v -> n `div` v) . factors
          toSum k = let v = n `div` k in v * (v - 1) `div` 2 * k + v

main = do
    [n] <- getIntegers
    printInts $ nub $ sort $ solve n

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int64
  putStrLn $ unwords $ map show $ map (\d -> d + (n * (d-1)) `shiftR` 1)
    $ divisors n

{-# INLINE divisors #-}
divisors :: (Integral i) => i -> [i]
divisors n = sort $ process 1 $ primeDecp n
  where
    process !x ((p,n):ps) = do
      pk <- take (n+1) $ iterate (p*) 1
      process (x*pk) ps
    process !x [] = return x

{-# INLINE primeDecp #-}
primeDecp :: (Integral i) => i -> [(i,Int)]
primeDecp n = let cons = (:); nil = [] in
  let (expt2,n1) = countExpt n 2
      loop p n rt | n == 1    = nil
                  | p > rt    = cons (n,1) nil
                  | expt > 0  = cons (p,expt) $ loop (p+2) n_ (sqrtInt n_)
                  | otherwise = loop (p+2) n rt
        where
          (expt,n_) = countExpt n p
  in (if expt2 > 0 then cons (2,expt2) else id)
     $ loop 3 n1 (sqrtInt n1)

{-# INLINE countExpt #-}
countExpt :: (Integral i) => i -> i -> (Int, i)
countExpt !x !base
  = (\(Just (!j,!q0,!q1,!r1)) -> (j,q0))
      $ find (\(!j,!q0,!q1,!r1) -> r1 /= 0) divlist
  where
    (!q0,!r0) = x `divMod` base
    divlist = iterate (\(!j,!q0,!q1,!r1) -> let (q2,r2) = q1 `divMod` base
                                            in (j+1,q1,q2,r2))
              (0,x,q0,r0)

{-# INLINE sqrtInt #-}
sqrtInt :: (Integral i) => i -> i
sqrtInt x = ceiling $ sqrt (fromIntegral x :: Double)

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  putStrLn $ unwords $ map show $ map (\d -> d + (n * (d-1)) `shiftR` 1)
    $ divisors n

{-# INLINE divisors #-}
divisors :: (Integral i) => i -> [i]
divisors n = sort $ process 1 $ primeDecp n
  where
    process !x ((p,n):ps) = do
      pk <- take (n+1) $ iterate (p*) 1
      process (x*pk) ps
    process !x [] = return x

{-# INLINE primeDecp #-}
primeDecp :: (Integral i) => i -> [(i,Int)]
primeDecp n = let cons = (:); nil = [] in
  let (expt2,n1) = countExpt n 2
      loop p n rt | n == 1    = nil
                  | p > rt    = cons (n,1) nil
                  | expt > 0  = cons (p,expt) $ loop (p+2) n_ (sqrtInt n_)
                  | otherwise = loop (p+2) n rt
        where
          (expt,n_) = countExpt n p
  in (if expt2 > 0 then cons (2,expt2) else id)
     $ loop 3 n1 (sqrtInt n1)

{-# INLINE countExpt #-}
countExpt :: (Integral i) => i -> i -> (Int, i)
countExpt !x !base
  = (\(Just (!j,!q0,!q1,!r1)) -> (j,q0))
      $ find (\(!j,!q0,!q1,!r1) -> r1 /= 0) divlist
  where
    (!q0,!r0) = x `divMod` base
    divlist = iterate (\(!j,!q0,!q1,!r1) -> let (q2,r2) = q1 `divMod` base
                                            in (j+1,q1,q2,r2))
              (0,x,q0,r0)

{-# INLINE sqrtInt #-}
sqrtInt :: (Integral i) => i -> i
sqrtInt x = floor $ sqrt (fromIntegral x :: Double)

{-# LANGUAGE BangPatterns #-}
import System.IO
import Control.Applicative
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import Data.ByteString.Lazy.Builder
import Data.ByteString.Lazy.Builder.ASCII
import qualified Data.Map as Map
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]
construct reader str
    | BS.null str = []
    | isSpace (BS8.head str) = construct reader (BS8.tail str)
    | otherwise = let Just (i, other) = reader str in i : construct reader other

getInts :: IO [Int]
getInts = construct BS8.readInt <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = construct BS8.readInteger <$> BS.getLine

printInts :: [Int] -> IO ()
printInts = putStrLn . intercalate " " . map show

solve n = map toSum $ concat [factors n, factors2 n]
    where cand n = takeWhile (\i -> i * i <= n) [1..]
          factors n = filter (\k -> n `mod` k == 0) $ cand n
          factors2 = map (\v -> n `div` v) . factors
          toSum k = let v = n `div` k in v * (v - 1) `div` 2 * k + v

main = do
    [n] <- getInts
    printInts $ nub $ sort $ solve n


solve :: [Int] -> [Int]
solve [a1,a2,a3,a4,a5] = [a1,a3,a5,a2,a4]
solve [a1,a2,a3,a4,a5,a6] = [a1,a4,a2,a5,a3,a6]
solve [a1,a2,a3,a4,a5,a6,a7] = [a1,a5,a2,a6,a3,a7,a4]
solve (a1:a2:a3:a4:as) = a2:a4:a1:a3: solve as
solve _ = []

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n:_) <- readNums
    case solve [1..n] of
        [] -> putStrLn "-1"
        ans -> putStrLn $ unwords $ map show ans
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readNums
    testCases t

readNums :: (Read n) => IO [n]
readNums = map read . words <$> getLine

import           Control.Arrow

main = interact $
  lines >>> drop 1 >>> map (read >>> solve >>> map show >>> unwords) >>> unlines

solve :: Int -> [Int]
solve 1 = [1]
solve n | n <= 3 = [-1]
solve n = [1, 3 .. n-4] ++ four [n-3 .. n] ++ reverse [2, 4 .. n-4]
  where
    four [a,b,c,d] = [b,d,a,c]

import Control.Monad

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

routine :: IO ()
routine = do
  n <- readLn
  putStrLn $ (unwords.map show) $ solve n

solve :: Int -> [Int]
solve n
  | n<4 = [-1]
  | otherwise = reverse (take l1 [1,3..]) ++ take l2 (4:2:[6,8..])
  where
    l1 = if even n
      then n `div` 2
      else (n+1) `div` 2
    l2 = n `div` 2

solve :: [Int] -> [Int]
solve [a1,a2,a3,a4,a5] = [a1,a3,a5,a3,a4]
solve [a1,a2,a3,a4,a5,a6] = [a1,a4,a2,a5,a3,a6]
solve [a1,a2,a3,a4,a5,a6,a7] = [a1,a5,a2,a6,a3,a7,a4]
solve (a1:a2:a3:a4:as) = a2:a4:a1:a3: solve as
solve _ = []

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n:_) <- readNums
    case solve [1..n] of
        [] -> putStrLn "-1"
        ans -> putStrLn $ unwords $ map show ans
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readNums
    testCases t

readNums :: (Read n) => IO [n]
readNums = map read . words <$> getLine


import Data.Array
import Data.List

main=interact $ show . f . lines
f (nm:field) = sum [ (table1!i - 1) * (table2!j - 1) |
  (i, line) <- zip [1..] field, (j, '*') <- zip [1..] line ]
  where
  [n,m] = map read $ words nm
  table1 = listArray (1, n) [ sum [ 1 | '*' <- line ] | line <- field ]
  table2 = listArray (1, m) [ sum [ 1 | '*' <- line ] | line <- transpose field ]

import Control.Monad
import Data.Array
import Data.List

main = do
	[n, m] <- fmap (map read . words) getLine
	a <- replicateM n getLine
	putStrLn $ show $ gao n m a

gao n m a = sum [row!i * col!j | i <- [1 .. n], j <- [1 .. m], mat!(i,j) == '*'] where
	cnt l = listArray (1, length l) $ map (toInteger . pred . length . filter (=='*')) $ l
	row = cnt a
	col = cnt $ transpose a
	mat = listArray ((1,1), (n,m)) $ concat a

import Control.Monad
import Data.Array
import Data.Int
import Data.List

main = do
	[n, m] <- fmap (map read . words) getLine
	a <- replicateM n getLine
	putStrLn $ (show::Int64->String) $ gao n m a

gao n m a = sum [row!i * col!j | i <- [1 .. n], j <- [1 .. m], mat!(i,j) == '*'] where
	cnt l = listArray (1, length l) $ map (fromIntegral . pred . length . filter (=='*')) $ l
	row = cnt a
	col = cnt $ transpose a
	mat = listArray ((1,1), (n,m)) $ concat a

module Main where

import Control.Monad
import Data.List

main = do
    [h, w] <- ( map read . words ) `liftM` getLine
    board <- replicateM h getLine
    --let (h, w) = (1000, 1000)
        --board = replicate h ( replicate w '*' )
    let rowCount = map (fromIntegral . length . filter (=='*')) board
        colCount = foldl' (\colCount row -> zipWith (\c ch -> if ch == '*' then c+1 else c) colCount row) (replicate w 0) board
        rowRes = zipWith (\row rowCount ->
                ( foldl' (\acc (ch, colCount) -> acc +
                        if ch == '*'
                        then (colCount-1) * (rowCount-1)
                        else 0
                    ) 0 (zip row colCount) )
            ) board rowCount
        res = sum rowRes

    --putStrLn $ show rowCount
    --putStrLn $ show colCount
    --putStrLn $ show rowRes
    putStrLn $ show res

module Main where

import Control.Monad
import Data.List
import Data.Array
import Data.Int
import Debug.Trace

readI :: String -> Int
readI = read

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

main = do
    [n, m] <- getLine >>= return . readL
    ss <- getContents >>= return . (take n) . lines
    print $ solve n m ss

solve n m ss = parser ss where
    ms = listArray (0, m-1) $ map count (transpose ss)
    mj j = fromIntegral (ms!j - 1)

    parser ss = parser' ss 0 where

        parser' :: [String] -> Int64 -> Int64
        parser' []     acc = acc
        parser' (s:ss) acc = if n > 0
            then parser' ss (acc + n*(sum $ map mj $ findIndices (=='*') s))
            else parser' ss acc
            where n = fromIntegral (count s - 1)

count s = length $ filter (=='*') s

import Data.List
import Data.Int

solve arr = sum $ zipWith (*) row $ map (sum . zipWith (\x y -> if y=='*' then x else 0) col) arr
  where
    mapping :: [[Char]] -> [Int64]
    mapping = map ((\x -> fromIntegral x - 1) . length . filter (=='*'))
    row = mapping arr
    col = mapping $ transpose arr

main = do
    arr <- fmap (tail.lines) getContents
    print $ solve arr

{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Int

solve arr = sum $ zipWith (*) row $ map (sum . zipWith (\x y -> if y=='*' then x else 0) col) arr
  where
    mapping = map ((\x -> fromIntegral x - 1) . length . filter (=='*'))
    row = mapping arr :: [Int64]
    col = mapping $ transpose arr

main = do
    arr <- fmap (tail . lines) getContents
    print $ solve arr

module Main where

import Control.Monad
import Data.List

main = do
    --[h, w] <- ( map read . words ) `liftM` getLine
    --board <- replicateM h getLine
    let (h, w) = (1000, 1000)
        board = replicate h ( replicate w '*' )
    let rowCount = map (fromIntegral . length . filter (=='*')) board
        colCount = foldl' (\colCount row -> zipWith (\c ch -> if ch == '*' then c+1 else c) colCount row) (replicate w 0) board
        rowRes = zipWith (\row rowCount ->
                ( foldl' (\acc (ch, colCount) -> acc +
                        if ch == '*'
                        then (colCount-1) * (rowCount-1)
                        else 0
                    ) 0 (zip row colCount) )
            ) board rowCount
        res = sum rowRes

    --putStrLn $ show rowCount
    --putStrLn $ show colCount
    --putStrLn $ show rowRes
    putStrLn $ show res

import Data.Array
import Data.List

main=interact $ show . f . lines
f (nm:field) = sum [ (table1!i - 1) * (table2!j - 1) |
  (i, line) <- zip [1..] field, (j, '*') <- zip [1..] line ]
  where
  [n,m] = map read $ words nm
  table1 = listArray (1, n) $ map (length . filter (=='*')) field
  table2 = listArray (1, m) $ map (length . filter (=='*')) $ transpose field

module Main where

import Control.Monad
import Data.List
import Data.Array
import Debug.Trace

readI :: String -> Int
readI = read

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

main = do
    [n, m] <- getLine >>= return . readL
    ss <- getContents >>= return . (take n) . lines
    print $ solve n m ss

solve n m ss = parser ss where
    ms = listArray (0, m-1) $ map count (transpose ss)
    mj j = (ms!j) - 1

    parser ss = parser' ss 0 where

        parser' []     acc = acc
        parser' (s:ss) acc = if n > 1
            then parser' ss (acc + (n-1)*(sum $ map mj $ findIndices (=='*') s))
            else parser' ss acc
            where n = count s

count s = length $ filter (=='*') s


import           Control.Monad

main :: IO()
main =
  do
    x <- read <$> getLine
    replicateM_ x solve

solve :: IO()
solve =
  do
    [a, b, n, m] <- map read . words <$> getLine :: IO [Integer]
    let c = min a b
    if c >= m && a + b >= n + m
      then
        putStrLn "Yes"
      else
        putStrLn "No"

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

main = getLine >>= flip replicateM_ test . read

test = do
  [a, b, n, m] <- map read . words <$> getLine
  putStrLn $ bool "No" "Yes" $ a + b >= n + m && min a b >= m

import           Control.Monad

main :: IO()
main =
  do
    x <- read <$> getLine
    replicateM_ x solve

solve :: IO()
solve =
  do
    [a, b, n, m] <- map read . words <$> getLine :: IO [Integer]
    let c = min a b
    if c >= m && a + b >= n + m
      then
        print "Yes"
      else
        print "No"


-- import Debug.Trace

type InType  = (Integer, Integer, Integer, Integer)
type OutType = Integer

inpLines :: Int
inpLines = 1

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

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

solve :: InType -> OutType
solve (p,a,b,c) = minimum [go a, go b, go c]
    where go x = if p `mod` x == 0
                 then 0
                 else x - (p `mod` x)

receive :: [String] -> InType
receive [s] = (p,a,b,c)
    where [p,a,b,c] = toArr s

main :: IO ()
main = interact (unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines)

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

import Data.Int

ceilDiv :: Integral t => t -> t -> t
ceilDiv n k = div (n + k - 1) k

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [p, a, b, c] <- readInts
    let  tar = minimum [xi * ceilDiv p xi | xi <- [a, b, c]]
    -- ??? How is this wrong?
    putInt64s [tar - p]

type SIO = StateT P.ByteString IO

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

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

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

import Control.Monad

main = nCases $ do
  [p, a, b, c] <- line
  print $ min (next p a) (min (next p b) $ next p c) - p

next p n = n * (p `updiv` n)
updiv a b = (a + b - 1) `div` b
line = fmap read . words <$> getLine
nCases a = readLn >>= flip replicateM_ a

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

import Control.Applicative
import Control.Exception (assert)
import Control.Monad
import Control.Monad.State
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Bits
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
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.Ord
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
  ~[p, a, b, c] <- popIntegers
  return $ bshow (solve p a b c)

solve p a b c = minimum $ map f [a, b, c]
  where
    f x = case p `quotRem` x of
            (_, 0) -> 0
            (q, _) -> (q + 1) * x - p

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

import Data.Int

ceilDiv :: Integral t => t -> t -> t
ceilDiv n k = div (n + k - 1) k

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [p, a, b, c] <- readInts
    let  tar = minimum [xi * ceilDiv p xi | xi <- [a, b, c]]
    putInt64s [tar - p]

type SIO = StateT P.ByteString IO

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

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

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

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

ceilDiv :: Integral t => t -> t -> t
ceilDiv n k = div (n + k - 1) k

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [p, a, b, c] <- readInts
    let  tar = minimum [xi * ceilDiv p xi | xi <- [a, b, c]]
    putInts [tar - p]

type SIO = StateT P.ByteString IO

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 Debug.Trace

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

inpLines :: Int
inpLines = 1

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

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

solve :: InType -> OutType
solve (p,a,b,c) = minimum [go a, go b, go c]
    where go x = if p `mod` x == 0
                 then 0
                 else x - (p `mod` x)

receive :: [String] -> InType
receive [s] = (p,a,b,c)
    where [p,a,b,c] = toArr s

main :: IO ()
main = interact (unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines)


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

import Data.Int
import Data.Char
import Data.Array.Unboxed
import Data.Bits

type Sparse = Array Int (UArray Int Int64)

bitFloor :: Int -> Int
bitFloor x
  = 1 `shift` (finiteBitSize (undefined :: Int) - countLeadingZeros x - 1)

query :: Sparse -> Int -> Int -> Int64
query st i j = let
  w = j - i
  sw = bitFloor w
  layer = countTrailingZeros sw
  in  gcd (st ! layer ! i) (st ! layer ! (j  - sw))

tstep :: UArray Int Int64 -> Int -> UArray Int Int64
tstep arr ss = let
  (p, q) = bounds arr
  in  array (p, q - ss) $ do
  i <- [p .. q - ss]
  pure $ (i, gcd (arr ! i) (arr ! (i + ss)))

mkSparse :: UArray Int Int64 -> Sparse
mkSparse arr = let
  (p, q) = bounds arr
  lastLayer = countTrailingZeros $ bitFloor $ q + 1 - p
  vs = iterate (* 2) 1
  in  listArray (0, lastLayer) $ scanl tstep arr $ take lastLayer vs

parseN :: Num t => P.ByteString -> t
parseN = let
  step x c = x * 10 + fromIntegral (ord c - ord '0')
  in  P.foldl' step 0

readNs :: Num t => SIO [t]
readNs = map parseN . P.words <$> readLine

binS :: (Int -> Bool) -> Int -> Int -> Int
binS fun x y = if  x == y
  then  x
  else  let
  z = div (x + y + 1) 2
  in  if  fun z
  then  binS fun x (z-1)
  else  binS fun z y

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n] <- readInts
    aLi <- readNs :: SIO [Int64]
    let
      v = listArray (1, n-1) $ zipWith (\x y -> abs (x - y)) aLi (tail aLi)
      tv = mkSparse v
      ans = foldl' max 1 $ do
        i <- [1 .. n-1]
        let  stop = binS (\j -> query tv i j == 1) i n
        pure $ stop - i + 1
    putInts [ans]

type SIO = StateT P.ByteString IO

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

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Monad (foldM_, forM_, replicateM, guard)
import Control.Monad.ST
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.Array as A
import Data.Array.Base ((!))
import Data.Array.ST
import qualified Data.Array.Unboxed as U
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Int
import Data.Maybe (fromJust)

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

testCase :: Scanner String
testCase = show . solve <$> numberOf (fromIntegral <$> integer)

type ArrayI64 = U.UArray Int Int64
type ArrayInt = U.UArray Int Int

lg = 20
lim = 2 * 10^5 + 5
logs :: ArrayInt
logs = U.array (1, lim) $ do
  l <- [0 .. lg]
  i <- [2 ^ l .. 2 ^ (l + 1) - 1]
  guard $ i <= lim
  return (i, l)

solve :: [Int64] -> Int
solve [_] = 1
solve xs = (1 +) . maximum $ map computeAt [0 .. n - 1]
  where
    n = length xs - 1

    computeAt i = min (i + 1) . foldl pick 0 $ reverse [0 .. lg - 1]
      where
        pick len j =
          let l = max 0 $ i - len - 2 ^ j + 1
              g = rangeGCD l i
           in len + (if g == 1 then 0 else 2 ^ j)

    -- adjacent differences
    diffs :: ArrayI64
    diffs = U.listArray (0, n - 1) $ map abs $ zipWith (-) xs (tail xs)

    -- rangeGCD l r = gcd a[l..r]
    --(j, l') = maximum [(j, l') | j <- [0..lg], let l' = l + 2^j - 1, l' <= r]
    rangeGCD :: Int -> Int -> Int64
    rangeGCD l r =
      let j = logs ! (r - l + 1)
          l' = l + 2 ^ j - 1
       in gcd (sparseGCD ! r ! j) (sparseGCD ! l' ! j)

    -- sparseGCD ! i ! j = gcd a[i - 2^j + 1 .. i]
    sparseGCD :: A.Array Int ArrayI64
    sparseGCD = runST $ do
      let nil = U.listArray (0, lg - 1) $ replicate lg 0
      gcds <- newArray (0, n - 1) nil :: ST s (STArray s Int ArrayI64)

      forM_ [0 .. n - 1] $ \i -> do
        cur <- thaw nil :: ST s (STUArray s Int Int64)
        writeArray cur 0 (diffs ! i)
        forM_ [1 .. lg - 1] $ \j -> do
          a <- readArray cur (j - 1)
          bs <- readArray gcds $ max 0 (i - 2 ^ (j - 1))
          let b = bs ! (j - 1)
          writeArray cur j $ gcd a b
        freeze cur >>= writeArray gcds i

      freeze gcds

foldM_' b ta f = foldM_ f b ta

-------------------------- 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 (,)

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Control.Applicative (liftA2)
import Control.Monad (forM_, replicateM)
import Control.Monad.ST
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.Array as A
import Data.Array.Base ((!))
import Data.Array.ST
import qualified Data.Array.Unboxed as U
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Int
import Data.Maybe (fromJust)
import Debug.Trace (trace)

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

testCase :: Scanner String
testCase = show . solve <$> numberOf (fromIntegral <$> integer)

type ArrayI64 = U.UArray Int Int64

solve :: [Int64] -> Int
solve [_] = 1
solve xs = (1+) . maximum $ debug $ map computeAt [0 .. n -1]
  where
    n = length xs - 1
    lg = 3

    computeAt i = min (i + 1) . foldl pick 0 $ reverse [0 .. lg - 1]
      where
        pick len j =
          let l = max 0 $ i - len - 2^j + 1
              g = rangeGCD l i
           in len + (if g == 1 then 0 else 2^j)

    -- adjacent differences
    diffs :: ArrayI64
    diffs = debug $ U.listArray (0, n - 1) $ map abs $ zipWith (-) xs (tail xs)

    -- rangeGCD l r = gcd a[l..r]
    rangeGCD :: Int -> Int -> Int64
    rangeGCD l r =
      let (j, l') = maximum [(j, l') | j <- [0..lg], let l' = l + 2^j - 1, l' <= r]
       in gcd (sparseGCD ! r ! j) (sparseGCD ! l' ! j)

    -- sparseGCD ! i ! j = gcd a[i - 2^j + 1 .. i]
    sparseGCD :: A.Array Int ArrayI64
    sparseGCD = debug $ runST $ do
      let nil = U.listArray (0, lg - 1) $ replicate lg 0
      gcds <- newArray (0, n - 1) nil :: ST s (STArray s Int ArrayI64)

      forM_ [0 .. n - 1] $ \i -> do
        cur <- thaw nil :: ST s (STUArray s Int Int64)
        writeArray cur 0 (diffs ! i)
        forM_ [1 .. lg - 1] $ \j -> do
          a <- readArray cur (j - 1)
          bs <- readArray gcds $ max 0 (i - 2 ^ (j - 1))
          let b = bs ! (j - 1)
          writeArray cur j $ gcd a b
        freeze cur >>= writeArray gcds i

      freeze gcds

-------------------------- Template ------------------------------------------
-- debug a = trace (show a) a
debug a = a

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 (,)


import Control.Monad (replicateM_)
import Data.Bits (xor)
import Data.List (foldl')

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

countSegment :: (Int, Int, Int) -> Int -> (Int, Int, Int)
countSegment (xored, cnt, y) x = (xored', cnt', y) where
  (xored', cnt') = if xored `xor` x == y
    then (0, cnt + 1)
    else (xored `xor` x, cnt)

isPossible :: [Int] -> Bool
isPossible xs = xored == 0 || let (_, cnt, _) = getCnt xs in cnt >= 3 where
  xored = foldl' xor 0 xs
  getCnt :: [Int] -> (Int, Int, Int)
  getCnt = foldl' countSegment (0, 0, xored)

solve :: IO ()
solve =
  getLine  >>
  isPossible <$> readInts >>= \ans ->
  putStrLn $ if ans then "YES" else "NO"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

{-# LANGUAGE BlockArguments #-}

import Data.Bits
import Data.List
import Data.Array
import Prelude
import Data.Bool
import Control.Monad
import Control.Applicative

precalc :: Int -> [Int] -> Int -> Int -> Int
precalc len x = \l r -> (arr ! (l - 1)) `xor` (arr ! r)
  where
    arr = listArray (0, len) $ scanl' xor 0 x

solve :: Int -> [Int] -> Bool
solve len x = any (\m -> get 1 m == get (m + 1) len || any (\m' -> get 1 m == get (m + 1) m' && get m m' == get (m' + 1) len) [m..len - 1]) [1..len - 1]
  where
    get = precalc len x

main :: IO ()
main = readLn >>= flip replicateM_ do putStrLn . bool "NO" "YES" =<< liftA2 solve readLn (fmap read . words <$> getLine)

import Data.Bits
import Data.List
import Data.Array
import Prelude
import Data.Bool

precalc :: [Int] -> Int -> Int -> Int
precalc x = \l r -> (arr ! (l - 1)) `xor` (arr ! r)
  where
    arr = listArray (0, len) $ scanl' xor 0 x
    len = length x

solve :: [Int] -> Bool
solve x = any (\m -> get 1 m == get (m + 1) len || any (\m' -> get 1 m == get (m + 1) m' && get m m' == get (m' + 1) len) [m..len - 1]) [1..len - 1]
  where
    len = length x
    get = precalc x

main :: IO ()
main = interact $ unlines . fmap (bool "NO" "YES" . solve . fmap read . words) . evens . tail . lines

evens :: [a] -> [a]
evens (_:x:xs) = x:evens xs
evens _        = []

import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S

import qualified Data.Array as A

import Data.Bits(xor)

import Data.Array((!))

result2 list = 0 == foldr xor 0 list

result3 [x, y] = False
result3 [x, y, z] = x == y && x == z

result3 list = foldr aux0 False [1..(n-2)] where
	xorList [] = []
	xorList [x] = [x]
	xorList (x:y:xs) = let l = xorList $ y:xs in (xor x $ head l) : l
	xorA = A.listArray (0, n) $ xorList list

	n = toInteger $ length list

	aux0 i b = foldr (aux1 i) b [(i+1)..(n-1)]

	aux1 i j b = (||) b $ x0 == x1 && x0 == x2 where
		x0 = xor v0 vi
		x1 = xor vi vj
		x2 = vj

		v0 = xorA ! 0
		vi = xorA ! i
		vj = xorA ! j

showR True = "YES"
showR False = "NO"

main = do
	t <- getLine >>= return . read :: IO Integer
	let loop t = if t == 0 then return () else do
		n <- getLine >>= return . read :: IO Integer
		a <- getLine >>= return . (fmap read) . words :: IO [Integer]
		putStrLn $ showR $ result2 a || result3 a
		loop $ t - 1
	loop t

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BlockArguments #-}

import Data.Bits
import Data.List
import Data.Array
import Prelude
import Data.Bool
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import Data.Maybe

precalc :: Int -> [Int] -> Int -> Int -> Int
precalc len x = \l r -> (arr ! (l - 1)) `xor` (arr ! r)
  where
    arr = listArray (0, len) $ scanl' xor 0 x

solve :: Int -> [Int] -> Bool
solve len x = any (\m -> get 1 m == get (m + 1) len || any (\m' -> get 1 m == get (m + 1) m' && get m m' == get (m' + 1) len) [m..len - 1]) [1..len - 1]
  where
    get = precalc len x

main :: IO ()
main = readLn >>= flip replicateM_ do putStrLn . bool "NO" "YES" =<< liftA2 solve readLn readInts

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

import Data.Bits
import Data.List
import Data.Array
import Prelude
import Data.Bool

precalc :: [Int] -> Int -> Int -> Int
precalc x = \l r -> (arr ! l) `xor` (arr ! r - 1)
  where
    arr = listArray (0, len) $ scanl' xor 0 x
    len = length x

solve :: [Int] -> Bool
solve x = any (\m -> get 1 m == get m len || any (\m' -> get 1 m == get m m' && get m m' == get m' len) [m..len]) [1..len]
  where
    len = length x
    get = precalc x

main :: IO ()
main = interact $ unlines . fmap (bool "NO" "YES" . solve . fmap read . words) . evens . tail . lines

evens :: [a] -> [a]
evens (_:x:xs) = x:evens xs
evens _        = []

import Data.Bits
import Data.List
import Data.Array
import Prelude
import Data.Bool

precalc :: [Int] -> Int -> Int -> Int
precalc x = \l r -> (arr ! l) `xor` (arr ! r)
  where
    arr = listArray (0, len) $ scanl' xor 0 x
    len = length x

solve :: [Int] -> Bool
solve x = any (\m -> get 1 m == get m len || any (\m' -> get 1 m == get m m' && get m m' == get m' len) [m..len]) [1..len]
  where
    len = length x
    get = precalc x

main :: IO ()
main = interact $ unlines . fmap (bool "NO" "YES" . solve . fmap read . words) . evens . tail . lines

evens :: [a] -> [a]
evens (_:x:xs) = x:evens xs
evens _        = []

import Control.Monad (replicateM_)
import Data.Bits (xor)
import Data.List (foldl')

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

countSegment :: (Int, Int, Int) -> Int -> (Int, Int, Int)
countSegment (xored, cnt, y) x = (xored', cnt', y) where
  (xored', cnt') = if xored `xor` x == y
    then (xored `xor` x, cnt + 1)
    else (0, cnt)

isPossible :: [Int] -> Bool
isPossible xs = xored == 0 || let (_, cnt, _) = getCnt xs in cnt >= 3 where
  xored = foldl' xor 0 xs
  getCnt :: [Int] -> (Int, Int, Int)
  getCnt = foldl' countSegment (0, 0, xored)

solve :: IO ()
solve =
  getLine  >>
  isPossible <$> readInts >>= \ans ->
  putStrLn $ if ans then "YES" else "NO"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

import Control.Monad (replicateM_)
import Data.Bits (xor)
import Data.List (foldl')

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

countSegment :: (Int, Int, Int) -> Int -> (Int, Int, Int)
countSegment (xored, cnt, y) x = (xored', cnt', y) where
  xored' = xored `xor` x
  cnt' = if xored' == y then cnt + 1 else 0

isPossible :: [Int] -> Bool
isPossible xs = xored == 0 || let (_, cnt, _) = getCnt xs in cnt >= 3 where
  xored = foldl' xor 0 xs
  getCnt :: [Int] -> (Int, Int, Int)
  getCnt = foldl' countSegment (0, 0, xored)

solve :: IO ()
solve =
  getLine  >>
  isPossible <$> readInts >>= \ans ->
  putStrLn $ if ans then "YES" else "NO"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve


module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

  readInt :: String -> Int
  readInt s = read s :: Int

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  inv :: Char -> Char
  inv 'L' = 'R'
  inv 'R' = 'L'
  inv 'U' = 'D'
  inv 'D' = 'U'
  inv 'Q' = 'Q'

  separation :: Char -> Char -> String -> Int -> Int
  separation _ _ [] i = i
  separation 'Q' 'Q' (x:xs) i
    | x == 'U' = separation 'Q' 'U' xs i
    | x == 'D' = separation 'Q' 'D' xs i
    | x == 'R' = separation 'R' 'Q' xs i
    | x == 'L' = separation 'L' 'Q' xs i
  separation 'Q' u (x:xs) i
    | x == 'R' = separation 'R' u xs i
    | x == 'L' = separation 'L' u xs i
    | x == inv u = separation 'Q' x xs (i + 1)
    | otherwise = separation 'Q' u xs i
  separation r 'Q' (x:xs) i
    | x == 'U' = separation r 'U' xs i
    | x == 'D' = separation r 'D' xs i
    | x == inv r = separation x 'Q' xs (i + 1)
    | otherwise = separation r 'Q' xs i
  separation r u (x:xs) i
    | x == inv r = separation x 'Q' xs (i + 1)
    | x == inv u = separation 'Q' x xs (i + 1)
    | otherwise = separation r u xs i

  main :: IO()
  main = do
    i <- getLine >>= return . readInt
    moves <- getLine
    putStrLn $ show $ separation 'Q' 'Q' moves 1

import Data.List( nub)
main = do
    n_ <- readLn::IO Int
    direcs_ <- getLine
    let proc (d:[]) stop
	  | d `elem` stop   = 1
	  | otherwise	    = 0
	proc (d1:d2:ds) stop
	  | d1 `elem` stop = 1+(proc (d2:ds) $ nub $ (opp d1):[])
	  | otherwise	    = proc (d2:ds) $ nub $ (opp d1):stop
	opp 'L' = 'R'
	opp 'R' = 'L'
	opp 'D' = 'U'
	opp 'U' = 'D'
    print $ (proc direcs_ [])+1


main = do
     dummy <- getLine
     a <- fmap (fmap read . words) getLine
     let b = scanl (+) 0 a
         alice = bsearch b 0 $ length a
         bob = length a - alice
     putStrLn $ show alice ++ " " ++ show bob
     where bsearch b l r
                   | l >= r = l
                   | otherwise = let m = (l+r) `div` 2
                                 in  if b!!m <= last b-b!!(m+1) then bsearch b (m+1) r else bsearch b l m

module Main where

import qualified Data.ByteString.Char8 as BS
import Data.Maybe (fromJust)
import Data.Functor ((<&>))

main :: IO ()
main =  BS.getContents <&> solve . ints >>= putStrLn

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

solve :: [Int] -> String
solve (n:xs) = show x <> " " <> show y
  where
    greedy a b (x, y)
      | null a || null b || x + y == n = (x, y)
      | head a <= head b = greedy (tail a) b (x + 1, y)
      | otherwise = greedy a (tail b) (x, y + 1)
    (x, y) = greedy (scanl1 (+) xs) (scanl1 (+) (reverse xs)) (0, 0)

{-# LANGUAGE TypeApplications #-}
module Main where

main :: IO ()
main = interact solve

solve :: String -> String
solve input = show x <> " " <> show y
  where
    n:xs = map (read @Int) $ words input
    greedy a b (x, y)
      | null a || null b || x + y == n = (x, y)
      | head a <= head b = greedy (tail a) b (x + 1, y)
      | otherwise = greedy a (tail b) (x, y + 1)
    (x, y) = greedy (scanl1 (+) xs) (scanl1 (+) (reverse xs)) (0, 0)

{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC

solve 0 0 (gotA, remA) (gotB, remB) tot
    | gotA + gotB <= tot - 2    = solve (head remA) (head remB) (gotA + 1, tail remA) (gotB + 1, tail remB) tot
    | gotA + gotB == tot - 1    = (gotA + 1, gotB)
    | otherwise                 = (gotA, gotB)

solve tA 0 (stateA@(gotA, remA)) (gotB, remB) tot
    | gotA + gotB <= tot - 1    = solve tA (head remB) stateA (gotB + 1, tail remB) tot
    | otherwise                 = (gotA, gotB)

solve 0 tB (gotA, remA) (stateB@(gotB, remB)) tot
    | gotA + gotB <= tot - 1    = solve (head remA) tB (gotA + 1, tail remA) stateB tot
    | otherwise                 = (gotA, gotB)

solve tA tB stateA stateB tot
    | tA > tB                   = solve (tA - tB) 0 stateA stateB tot
    | otherwise                 = solve 0 (tB - tA) stateA stateB tot

main =
  do all <- BS.getContents
     let Just (tot, r1) = readInt all
     let (ls, _)  = readMany readInt r1
     let (totA, totB) = solve 0 0 (0, ls) (0, reverse ls) tot
     putStrLn (show totA ++ " " ++ show totB)
  where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
          Just (x, r) -> let (xs, t) = readMany readf r
                         in  (x : xs, t)
          Nothing     -> ([], s)

import qualified Data.ByteString.Char8 as B
readInt' :: B.ByteString -> Int
readInt' s = case B.readInt s of Just (n, _) -> n
solve :: [Int] -> (Int, Int)
solve (n:xs) = go alice bob (0, 0)
    where alice = scanl1 (+) xs
          bob   = scanl1 (+) (reverse xs)
          go [] _ r = r
          go _ [] r = r
          go a@(x:xs) b@(y:ys) (p, q)
            | p + q == n = (p, q)
            | otherwise = case compare x y of
                GT -> go a ys (p, q + 1)
                _  -> go xs b (p + 1, q)
main = putStrLn . (\(x, y) -> show x ++ " " ++ show y) . solve . map readInt' . B.words =<< B.getContents

import Control.Applicative
import Text.Printf

main :: IO ()
main = do
    n <- read <$> getLine
    ps <- map read . words <$> getLine
    let (alice, chokudai) = calc n ps
    printf "%d %d\n" alice chokudai

calc :: Int -> [Int] -> (Int, Int)
calc n ps = (cnt, n - cnt)
    where
    total = sum ps
    half = ceiling $ fromIntegral total / 2
    cnt = cnt' ps 0 0
    cnt' (x:xs) time c
        | eatAliceTime < half     = cnt' xs eatAliceTime (c + 1)
        | time <= eatChokudaiTime = c + 1
        | otherwise               = c
        where
        eatAliceTime = x + time
        eatChokudaiTime = total - x - time

main = do
	dummy <- getLine
	line <- getLine
	putStrLn (let t = map read $ words line; a = gao t; b = length t - a in show a ++ " " ++ show b)

gao a = gao' 0 (length a) where
	b = 0: scanl1 (+) a
	s = last b
	gao' l r
		| l < r		= let m = (l + r) `div` 2 in if b!!m <= s - b!!(m+1) then gao' (m + 1) r else gao' l m
		| otherwise	= r

import Monad (liftM)

solve :: [Int] -> (Int, Int)
solve [x]  =  (1,0)
solve xs  =  solve' 0 0 xs (reverse xs)
  where
    n  =  length xs
    solve' a b (x:xs) (y:ys)
      | a + b >  n  =  error "a + b > n"
      | a + b == n  =  (a, b)
      | x >  y  =  solve' a (b+1) ((x-y):xs) ys
      | x <= y  =  solve' (a+1) b xs ((y-x):ys)

main :: IO ()
main  =  do
    getLine
    xs  <-  liftM (map read . words) getLine
    let (a, b)  =  solve xs
    putStrLn $ concat [show a, " ", show b]

import Data.List

main = do
  n <- readLn
  x <- getLine
  showSolve n x

showSolve :: Int -> String -> IO()
showSolve n x =
  let x1 = solve x
      x2 = n - x1
  in putStrLn ((show x1) ++ " " ++ (show x2))

solve :: String -> Int
solve x =
  let c = map read (words x)
      ct = mapAccumL (\x y -> (x+y, x+y)) 0 c
      avt = (fst ct) `div` 2
      ct2 = filter (<= avt) (snd ct)
      avt2 = if (null ct2) then 0 else (last ct2)
      p1 = length (ct2)
      p2 = if ((fst ct) - ((snd ct) !! p1)) >= avt2 then p1 + 1 else p1
  in p2

import Data.Sequence
import Prelude hiding (null)

type Chocos = Seq Int

data P = P Int Int

solve :: (P, P) -> Chocos -> (P, P)
solve p@(P anum aeating, P bnum beating) cs
    | null cs = p
    | aeating <= beating =
        let (aeating' :< cs') = viewl cs
        in solve (P (anum + 1) aeating', P bnum (beating - aeating)) cs'
    | aeating > beating =
        let (cs' :> beating') = viewr cs
        in solve (P anum (aeating - beating), P (bnum + 1) beating') cs'

main = do
    getLine -- n
    cs <- fmap (fromList . map read . words) getLine
    let (P anum _, P bnum _) = solve (P 0 0, P 0 0) cs
    putStrLn $ show anum ++ " " ++ show bnum

import Control.Applicative
import Control.Monad
import qualified Data.Sequence as Seq
import Text.Printf

type Time = Int
type Bars = Int
type State = (Seq.Seq Time, (Time, Bars), (Time, Bars))

eatThemAll' :: State -> State
eatThemAll' state@(s, alice@(t1, b1), bob@(t2, b2))
  | Seq.null s = state
  | t1 <= t2   = let t Seq.:< s' = Seq.viewl s in
                   eatThemAll' (s', (t1 + t, b1 + 1), bob)
  | otherwise  = let s' Seq.:> t = Seq.viewr s in
                   eatThemAll' (s', alice, (t2 + t, b2 + 1))

eatThemAll :: [Time] -> (Bars, Bars)
eatThemAll = do
  s <- Seq.fromList
  let (_, (_, b1), (_, b2)) = eatThemAll' (s, (0, 0), (0, 0))
  return (b1, b2)

solve :: [String] -> [String]
solve = fmap return $ do
  ts <- map read . words . head . drop 1
  let (b1, b2) = eatThemAll ts
  return $ printf "%d %d" b1 b2

main = interact $ unlines . solve . lines

import Data.List
main = do
    всегоПлиток <- readIO =<< getLine
    шоколадки <- (map read . words) `fmap` getLine
    let времяБоб = tail . reverse . scanl (+) 0 . reverse
        времяАлиса = scanl (+) 0
        съелаАлиса = length $ takeWhile (\(ал, б) -> ал <= б) $ zip (времяАлиса шоколадки)
                (времяБоб шоколадки)
    putStrLn $ unwords $ map show [съелаАлиса, всегоПлиток - съелаАлиса]

import Data.List
main = do
    всегоПлиток <- readIO =<< getLine
    шоколадки <- (map read . words) `fmap` getLine
    let времяБоб = tail . reverse . scanl (+) 0 . reverse
        времяАлиса = scanl (+) 0
        съелаАлиса = length $ takeWhile id $ zipWith (<=) (времяАлиса шоколадки)
                (времяБоб шоколадки)
    putStrLn $ unwords $ map show [съелаАлиса, всегоПлиток - съелаАлиса]

import Data.List

main = do
  n <- readLn
  x <- getLine
  showSolve n x

showSolve :: Int -> String -> IO()
showSolve n x =
  let x1 = solve x
      x2 = n - x1
  in putStrLn ((show x1) ++ " " ++ (show x2))

solve :: String -> Int
solve x =
  let c = map read (words x)
      ct = mapAccumL (\x y -> (x+y, x+y)) 0 c
      avt = (fst ct) `div` 2
      p1 = length (filter (<= avt) (snd ct))
      p2 = if ((fst ct) - ((snd ct) !! p1)) >= avt then p1 + 1 else p1
  in p2

import Data.List

main = do
  n <- readLn
  x <- getLine
  showSolve n x

showSolve :: Int -> String -> IO()
showSolve n x =
  let x1 = solve x
      x2 = n - x1
  in putStrLn ((show x1) ++ " " ++ (show x2))

solve :: String -> Int
solve x =
  let c = map read (words x)
      ct = mapAccumL (\x y -> (x+y, x+y)) 0 c
      avt = (fst ct) `div` 2
  in length (filter (<= avt) (snd ct))

import Data.List

main = do
  n <- readLn
  x <- getLine
  showSolve n x

showSolve :: Int -> String -> IO()
showSolve n x =
  let x1 = if (n > 1) then solve x else 1
      x2 = n - x1
  in putStrLn ((show x1) ++ " " ++ (show x2))

solve :: String -> Int
solve x =
  let c = map read (words x)
      ct = mapAccumL (\x y -> (x+y, x+y)) 0 c
      avt = (fst ct) `div` 2
  in length (filter (<= avt) (snd ct))

main = do
     dummy <- getLine
     a <- fmap (fmap read . words) getLine
     let b = scanl (+) 0 a
         alice = bsearch b 0 $ length a
         bob = length a - alice
     print $ show alice ++ " " ++ show bob
     where bsearch b l r
                   | l >= r = l
                   | otherwise = let m = (l+r) `div` 2
                                 in  if b!!m <= last b-b!!(m+1) then bsearch b (m+1) r else bsearch b l m

{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC

solve 0 0 (gotA, remA) (gotB, remB) tot
    | gotA + gotB <= tot - 2    = solve (head remA) (head remB) (gotA + 1, tail remA) (gotB + 1, tail remB) tot
    | gotA + gotB == tot - 1    = (gotA + 1, gotB)
    | otherwise                 = (gotA, gotB)

solve tA 0 (stateA@(gotA, remA)) (gotB, remB) tot
    | gotA + gotB <= tot - 1    = solve tA (head remB) stateA (gotB + 1, tail remB) tot
    | otherwise                 = (gotA, gotB)

solve 0 tB (gotA, remA) (stateB@(gotB, remB)) tot
    | gotA + gotB <= tot - 1    = solve (head remA) tB (gotA + 1, tail remA) stateB tot
    | otherwise                 = (gotA, gotB)

solve tA tB stateA stateB tot
    | tA > tB                   = solve (tA - tB) 0 stateA stateB tot
    | otherwise                 = solve 0 (tA - tB) stateA stateB tot

main =
  do all <- BS.getContents
     let Just (tot, r1) = readInt all
     let (ls, _)  = readMany readInt r1
     let (totA, totB) = solve 0 0 (0, ls) (0, reverse ls) tot
     putStrLn (show totA ++ " " ++ show totB)
  where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
          Just (x, r) -> let (xs, t) = readMany readf r
                         in  (x : xs, t)
          Nothing     -> ([], s)

{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC

solve 0  0 (stateA@(eatenA, remA)) (stateB@(eatenB, remB)) tot
    | eatenA + 1 + eatenB + 1 < tot - 1 = solve (head remA) (head remB) (eatenA + 1, tail remA) (eatenB + 1, tail remB) tot
    | eatenA + 1 + eatenB + 1 < tot     = (eatenA + 2, eatenB + 1)
    | otherwise                         = (eatenA + 1, eatenB + 1)
solve tA 0  (stateA@(eatenA, remA)) (eatenB, remB) tot
    | eatenA + eatenB + 1 < tot = solve tA (head remB) stateA (eatenB + 1, tail remB) tot
    | otherwise                 = (eatenA, eatenB + 1)
solve 0  tB (eatenA, remA) (stateB@(eatenB, remB)) tot
    | eatenA + 1 + eatenB < tot = solve (head remA) tB (eatenA + 1, tail remA) stateB tot
    | otherwise                 = (eatenA + 1, eatenB)
solve tA tB stateA stateB tot
    | tA > tB = solve (tA - tB) 0 stateA stateB tot
    | tA < tB = solve 0 (tA - tB)  stateA stateB tot

main =
  do all <- BS.getContents
     let Just (tot, r1) = readInt all
     let (ls, _)  = readMany readInt r1
     let (totA, totB) = solve 0 0 (0, ls) (0, reverse ls) tot
     putStrLn (show totA ++ " " ++ show totB)
  where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
          Just (x, r) -> let (xs, t) = readMany readf r
                         in  (x : xs, t)
          Nothing     -> ([], s)

import Control.Applicative
import Text.Printf

main :: IO ()
main = do
    n <- read <$> getLine
    ps <- map read . words <$> getLine
    let (alice, chokudai) = calc n ps
    printf "%d %d\n" alice chokudai

calc :: Int -> [Int] -> (Int, Int)
calc n ps = (cnt, n - cnt)
    where
    total = sum ps
    half = total `div` 2
    cnt = cnt' ps 0 0
    cnt' (x:xs) time c
        | eatAliceTime < half     = cnt' xs eatAliceTime (c + 1)
        | time <= eatChokudaiTime = c + 1
        | otherwise               = c
        where
        eatAliceTime = x + time
        eatChokudaiTime = total - x - time


import Data.Bits ((.|.))
import Data.List (foldl')

main :: IO ()
main = interact $ output . map solve . input

input :: String -> [[Integer]]
input = chunks . drop 1 . lines
  where
    chunks [] = []
    chunks (_:nums:ls) = let integers = map read $ words nums
                         in integers : chunks ls

output :: [Integer] -> String
output = unlines . map show

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

-- problem: https://codeforces.com/contest/1635/problem/A
-- origin: https://codeforces.com/contest/1635/submission/147037193

import Control.Monad.State (State, evalState, replicateM, state)
import Data.Bifunctor (first)
import Data.Bits (Bits ((.|.)))
import Data.Char (isDigit, isSpace)

getInt :: State [Char] Int
getInt = state (first (\x -> read x :: Int) . span isDigit . dropWhile isSpace)

mainFunc :: State [Char] [Char]
mainFunc = do
  t <- getInt
  fmap mconcat $
    replicateM t $ do
      n <- getInt
      a <- replicateM n getInt
      let ans = foldl (.|.) 0 a in pure $ show ans ++ "\n"

main :: IO ()
main = do
  inp <- getContents
  putStr $ evalState mainFunc inp

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

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

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

str = string7

solve :: SP Builder
solve = do
  t <- getInt
  -- let t = 1
  fmap mconcat $ replicateM t $ do
    n <- getInt
    a <- replicateM n getInt
    pure $ putInts [foldl (.|.) 0 a]

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

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

tst = P.span (> ' ') . dropSpace

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

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

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

import Control.Monad (forM_)
import Data.List (sort)
import Data.Bits ( Bits((.|.)) )

solve = foldr1 (.|.)

main :: IO ()
main = do
    t <- readLn :: IO Int
    forM_ [1 .. t] $ \i -> do
        n <- readLn :: IO Int
        l <- getLine
        let arr = map read (words l) :: [Int]
        print $ solve $ reverse (sort arr)

import Data.Bits

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf i xs = take i xs : chunksOf i (drop i xs)

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

type InType  = [Int]
type OutType = Int

solve :: InType -> OutType
solve = foldr (.|.) 0

receive :: [String] -> InType
receive [_, s] = toArr s
receive _      = error "unknown input"

main :: IO ()
main = interact $ unlines . map (show . solve . receive) . chunksOf 2 . tail . lines

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

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

import Data.Bits

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    a <- replicateM n getInt
    pure $ putInts [foldl' (.|.) 0 a]

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

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

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

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

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

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