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

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

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

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

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

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

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

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

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

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

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

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

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

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

m :: Int64
m = 998_244_353

newtype M = M { unM :: Int64 }
  deriving (Eq, Ord)

mI :: Int -> M
mI = M . fromIntegral

instance Show M where
    show (M v) = "M" ++ show v

instance Num M where
    fromInteger n = M $ fromInteger (n `mod` fromIntegral m)

    (M a) + (M b) | a + b >= m = M $ a + b - m
    (M a) + (M b) = M $ a + b

    (M a) - (M b) | a - b < 0 = M $ m + a - b
    (M a) - (M b) = M $ a - b

    (M a) * (M b) = M $ (a * b) `mod` m

    abs    = id
    signum = undefined

powM :: M -> Int64 -> M
powM a@(M ma) x
    | x == 0 = M 1
    | x == 1 = a
    | even x = let t = powM a (x `div` 2) in t * t
    | odd x = a * powM a (x - 1)

instance Fractional M where
    recip a = powM a $ m - 2
    fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)

type GraphA = A.Array Int [Int]

graphFromEdges :: Int -> [(Int, Int)] -> GraphA
graphFromEdges n edges = graph
    where
        graph = STA.runSTArray $ do
            graphA <- MA.newArray (1, n) ([] :: [Int])
            forM_ edges $ \(u, v) -> do
                modifyArray graphA u (v:)
                modifyArray graphA v (u:)
            return graphA

{- END OF GENERAL -}

solve :: Int -> Int -> [Int] -> [Int] -> Int64
solve n s as bs = unM $ solve' (M 0) (reverse abs) (reverse ms)
    where
        abs = sort $ zip as bs
        diffSL :: [Int] -> [Int] -> [Int]
        diffSL [] _ = []
        diffSL as [] = as
        diffSL as@(a:otherAs) bs@(b:otherBs)
            | a < b = a : diffSL otherAs bs
            | a == b = diffSL otherAs otherBs
            | a > b = diffSL as otherBs

        ms = diffSL [1 .. n] (sort bs)

        solve' :: M -> [(Int, Int)] -> [Int] -> M
        solve' k  [] _ = M 1
        solve' k abs@((a, b):otherABs) ms
            | b == -1 && L.null ms          = k * solve' (k - M 1) otherABs ms
            | b == -1 && head ms >= a - s   = solve' (k + M 1) abs (tail ms)
            | b == -1                       = k * solve' (k - M 1) otherABs ms
            | a - s > b                     = M 0
            | otherwise                     = solve' k otherABs ms

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, s] <- B8.getLine <&> readIntB8s
        as <- B8.getLine <&> readIntB8s
        bs <- B8.getLine <&> readIntB8s
        let answer = solve n s as bs
        printf "%lld\n" answer

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

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

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

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

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

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

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

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

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

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

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

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

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

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

m :: Int64
m = 998_244_353

newtype M = M { unM :: Int64 }
  deriving (Eq, Ord)

mI :: Int -> M
mI = M . fromIntegral

instance Show M where
    show (M v) = "M" ++ show v

instance Num M where
    fromInteger n = M $ fromInteger (n `mod` fromIntegral m)

    (M a) + (M b) | a + b >= m = M $ a + b - m
    (M a) + (M b) = M $ a + b

    (M a) - (M b) | a - b < 0 = M $ m + a - b
    (M a) - (M b) = M $ a - b

    (M a) * (M b) = let c = a * b in
        if c >= m
            then M $ c `mod` m
            else M c

    abs    = id
    signum = undefined

powM :: M -> Int64 -> M
powM a@(M ma) x
    | x == 0 = M 1
    | x == 1 = a
    | even x = let t = powM a (x `div` 2) in t * t
    | odd x = a * powM a (x - 1)

instance Fractional M where
    recip a = powM a $ m - 2
    fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)

type GraphA = A.Array Int [Int]

graphFromEdges :: Int -> [(Int, Int)] -> GraphA
graphFromEdges n edges = graph
    where
        graph = STA.runSTArray $ do
            graphA <- MA.newArray (1, n) ([] :: [Int])
            forM_ edges $ \(u, v) -> do
                modifyArray graphA u (v:)
                modifyArray graphA v (u:)
            return graphA

{- END OF GENERAL -}

solve :: Int -> Int -> [Int] -> [Int] -> Int64
solve n s as bs = unM $ solve' (M 0) (reverse abs) (reverse ms)
    where
        abs = sort $ zip as bs
        diffSL :: [Int] -> [Int] -> [Int]
        diffSL [] _ = []
        diffSL as [] = as
        diffSL as@(a:otherAs) bs@(b:otherBs)
            | a < b = a : diffSL otherAs bs
            | a == b = diffSL otherAs otherBs
            | a > b = diffSL as otherBs

        ms = diffSL [1 .. n] (sort bs)

        solve' :: M -> [(Int, Int)] -> [Int] -> M
        solve' k  [] _ = M 1
        solve' k abs@((a, b):otherABs) ms
            | b == -1 && L.null ms          = k * solve' (k - M 1) otherABs ms
            | b == -1 && head ms >= a - s   = solve' (k + M 1) abs (tail ms)
            | b == -1                       = k * solve' (k - M 1) otherABs ms
            | a - s > b                     = M 0
            | otherwise                     = solve' k otherABs ms

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, s] <- B8.getLine <&> readIntB8s
        as <- B8.getLine <&> readIntB8s
        bs <- B8.getLine <&> readIntB8s
        let answer = solve n s as bs
        printf "%lld\n" answer

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}

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

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

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

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

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

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

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

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

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

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

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

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

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

m :: Int64
m = 998_244_353

newtype M = M { unM :: Int64 }
  deriving (Eq, Ord)

mI :: Int -> M
mI = M . fromIntegral

instance Show M where
    show (M v) = "M" ++ show v

instance Num M where
    fromInteger n = M $ fromInteger (n `mod` fromIntegral m)

    (M a) + (M b) | a + b >= m = M $ a + b - m
    (M a) + (M b) = M $ a + b

    (M a) - (M b) | a - b < 0 = M $ m + a - b
    (M a) - (M b) = M $ a - b

    (M a) * (M b) = M $ (a * b) `mod` m

    abs    = id
    signum = undefined

powM :: M -> Int64 -> M
powM a@(M ma) x
    | x == 0 = M 1
    | x == 1 = a
    | even x = let t = powM a (x `div` 2) in t * t
    | odd x = a * powM a (x - 1)

instance Fractional M where
    recip a = powM a $ m - 2
    fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)

type GraphA = A.Array Int [Int]

graphFromEdges :: Int -> [(Int, Int)] -> GraphA
graphFromEdges n edges = graph
    where
        graph = STA.runSTArray $ do
            graphA <- MA.newArray (1, n) ([] :: [Int])
            forM_ edges $ \(u, v) -> do
                modifyArray graphA u (v:)
                modifyArray graphA v (u:)
            return graphA

{- END OF GENERAL -}

solve :: Int -> Int -> [Int] -> [Int] -> Int64
solve n s as bs = unM $ solve' 0 (reverse abs) (reverse ms)
    where
        abs = sort $ zip as bs
        diffSL :: [Int] -> [Int] -> [Int]
        diffSL [] _ = []
        diffSL as [] = as
        diffSL as@(a:otherAs) bs@(b:otherBs)
            | a < b = a : diffSL otherAs bs
            | a == b = diffSL otherAs otherBs
            | a > b = diffSL as otherBs

        ms = diffSL (sort as) (sort bs)

        solve' :: Int -> [(Int, Int)] -> [Int] -> M
        solve' k  [] _ = M 1
        solve' k (_:otherABs) [] = mI k * solve' (k - 1) otherABs []
        solve' k abs@((a, -1):otherABs) ms@(m:otherMs)
            | m >= a - s = solve' (k + 1) abs otherMs
            | otherwise  = mI k * solve' (k - 1) otherABs ms

        solve' k abs@((a, b):otherABs) ms
            | a - s > b = M 0
            | otherwise = solve' k otherABs ms

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, s] <- B8.getLine <&> readIntB8s
        as <- B8.getLine <&> readIntB8s
        bs <- B8.getLine <&> readIntB8s
        let answer = solve n s as bs
        printf "%lld\n" answer


import Control.Monad
import Data.Foldable

foldUntill :: Foldable t => (b -> Bool)-> (b -> a -> b) -> b -> t a -> Either (b,Maybe b,Maybe a) b
foldUntill predicate binary accumulator foldable =
  if predicate accumulator
    then Left (accumulator,Nothing,Nothing)
    else foldlM f accumulator foldable
  where
    f acc val =
      let
        newValue = binary acc val
        bool = predicate newValue
      in
        if bool
          then Left (newValue,Just acc,Just val)
          else Right newValue

type State = (Int , Indexed Int) -- (value , indexed maxval)
type Index = Int
type Indexed a = (Index, a)

solve :: Int -> [Int] -> Either (State, Maybe State, Maybe (Indexed Int)) State
solve p l = foldUntill predicate binary acc indexed
  where
    indexed = zip [1..] l
    acc = (0, (0,0))
    predicate (val,_)= val>p
    binary (summe,(ind,maks)) (ival,val) =let bigger = if val>maks then (ival,val) else (ind,maks) in  (summe + val, bigger )

analysis :: Either (State, Maybe State, Maybe (Indexed Int)) State -> Int
analysis (Right _) = 0
analysis (Left ((_,(index,_)),_,_)) = index

loesen :: Int -> [Int] -> Int
loesen p l = analysis $ solve p l

routine :: IO ()
routine = do
  [_,s] <- (map read . words) <$> getLine
  l <- (map read . words) <$> getLine
  print $ loesen s l

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

import Control.Monad
import Prelude
import Data.List
import Data.Int

testCase = do
    nsStr <- getLine
    aStr <- getLine
    let
        ns = map (read :: String -> Int64) (words nsStr)
        n = head ns
        s = head $ tail ns
        as = map (read :: String -> Int64) (words aStr) in do
        print $ solution s as

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()

prefixSumLessEq s [] = []
prefixSumLessEq s (h:t) = case s >= h of
    True -> h:(prefixSumLessEq (s - h) t)
    False -> []

solution s as = case sum as <= s of
    True -> 0
    False -> case elemIndex (sol s 0 0 as) as of
        Just x -> x + 1

sol s sm mx [] = 0
sol s sm mx (h:t) = result where
    mx2 = max mx h
    sm2 = sm + h
    result = case (sm2 - mx2) <= s of
        True -> max mx2 (sol s sm2 mx2 t)
        False -> mx

import Control.Monad
import Prelude
import Data.List

testCase = do
    nsStr <- getLine
    aStr <- getLine
    let
        ns = map (read :: String -> Int) (words nsStr)
        n = head ns
        s = head $ tail ns
        as = map (read :: String -> Int) (words aStr) in do
        print $ solution s as

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()

prefixSumLessEq s [] = []
prefixSumLessEq s (h:t) = case s >= h of
    True -> h:(prefixSumLessEq (s - h) t)
    False -> []

solution s as = case sum as <= s of
    True -> 0
    False -> case elemIndex (sol s 0 0 as) as of
        Just x -> x + 1

sol s sm mx [] = 0
sol s sm mx (h:t) = result where
    mx2 = max mx h
    sm2 = sm + h
    result = case (sm2 - mx2) <= s of
        True -> max mx2 (sol s sm2 mx2 t)
        False -> mx


import Control.Monad
import Data.List
import qualified Data.Map as Map
import qualified Data.Map.Strict as MapS

main = do
    t <- readLn
    replicateM_ t testcase

testcase :: IO ()
testcase = do
    firstLine <- getLine
    let [n,k] = map read . words $ firstLine
    putStrLn $ solve n k

solve :: Int -> Int -> String
solve n k
    | odd n = unwords . map show $ [1, (n-1) `div` 2, (n-1) `div` 2]
    | n `mod` 4 == 0 = unwords. map show $ [n `div` 2 , n `div` 4, n `div` 4]
    | otherwise = unwords. map show $ [2, (n-2) `div` 2, (n-2) `div` 2]

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

solve :: Int -> [Int]
solve n
  | odd n = 1 : replicate 2 (div n 2)
  | mod n 4 == 0 = div n 2 : replicate 2 (div n 4)
  | otherwise = 2 : replicate 2 (div n 2 - 1)

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, k] <- readInts
    putInts $ solve (n - (k - 3)) ++ replicate (k - 3) 1

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 BangPatterns #-}

import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List (group, sort)
import Data.Map ((!))
import qualified Data.Map as M
-- import Debug.Trace

import Data.Maybe (fromJust)
import System.IO
import Text.Read

getNums :: IO [Int]
getNums = do
  line <- B.getLine
  return $ map ((fst . fromJust) . B.readInt) . B.split ' ' $ line

main :: IO ()
main = do
  t <- readLn :: IO Integer
  forM_ [1 .. t] handleCase

handleCase :: Integer -> IO ()
handleCase c = do
  [n, k] <- getNums
  putStrLn $ unwords $ map show $ solve n k

solveEasy :: Int -> [Int]
solveEasy n
  | n `mod` 2 == 1 = [1, (n - 1) `div` 2, (n -1) `div` 2]
  | n `mod` 4 == 0 = [n `div` 2, n `div` 4, n `div` 4]
  | n `mod` 4 == 2 = [2, (n - 1) `div` 2, (n -1) `div` 2]

solve n k = replicate (k - 3) 1 ++ solveEasy (n - (k - 3))


import Control.Monad

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [x, y, k] <- map read . words <$> getLine :: IO [Integer]
    let
      sticksReq = k * (1 + y)
      ceilDiv p q = div (p + q - 1) q
      type1 = ceilDiv (sticksReq - 1) (x - 1)
      type2 = k
    print (type1 + type2)

module Main where

solve [x,y,k] =  (((y + 1) * k - 1 + x - 2) `div` (x - 1)) + k

main = do
   interact $ unlines . map (show . solve) . map ( map (read :: String -> Integer) . words ) . tail . lines

import Control.Monad
import Data.Array
import Data.Foldable
import Data.Graph
import Data.List

solve [a, b, c] = (b * c + c - 1 + a - 2) `div` (a - 1) + c

main = do
  a <- read <$> getLine
  replicateM_ a $ do
    i <- map read . words <$> getLine
    print $ solve i


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

import Data.Char
import Data.List
import qualified Data.Map as M
-- import Data.Map ((!))
import qualified Data.IntMap as IM
-- import Data.IntMap ((!))

import Data.Array
import Data.Function

import Debug.Trace

import Numeric

debug = flip trace
-- debug = const

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

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

double :: IO Double
double = read <$> getLine

doubles :: IO [Double]
doubles = map read . words <$> getLine

sum' = foldl' (+) 0
product' = foldl' (*) 1

fi = fromIntegral

calc :: Double -> Double -> Double -> (Int, Int)
calc n k t =
  let
    i = floor (n*t/100) + 1
    ai = floor (n*k*t/100 - (fi i - 1) * k)
  in (i, ai)

makeBar :: Double -> Double -> Int -> Int -> String
makeBar n k i ai =
  unwords . map show $ values
  where
    values :: [Int]
    values
      | n >= fi i = replicate (i - 1) (round k) ++ [ai] ++ replicate (round n - i) 0
      | otherwise = replicate (round n) (round k)

main = do
  [n, k, t] <- doubles
  let (i, ai) = calc n k t
  putStrLn $ makeBar n k i ai

main=getLine>>=putStrLn.unwords.slv.map read.words
slv :: [Int] -> [String]
slv (n:k:100:_) = map show $ replicate n k
slv (n:k:t:_) =
    map show $ replicate nFull k ++ [v] ++ replicate (n - nFull - 1) 0
    where
        nFull = p `div` k
        v = p `mod` k
        p = floor $ (fromIntegral k)*(fromIntegral n)*(fromIntegral t) / 100

module Main where

import Control.Monad

main = do
    [n, k, t] <- ( map read . words ) `liftM` getLine

    let a = n * t `div` 100
        m = ( n * t - 100 * a ) * k `div` 100
        out = unwords $ map show $ if a == n
            then replicate a k
            else replicate a k ++ [m] ++ replicate (n-a-1) 0

    putStrLn out

solve :: Int -> Int -> Int -> [Int]
solve n k t
	| t <= k = t:(take (n-1) (repeat 0))
	| otherwise = k:(solve (n-1) k (t-k))

main = do
	[n,k,t] <- getLine >>= return . map read . words
	putStrLn . unwords . map show $ solve n k ((n*k)*t`div`100)

printAns :: Int -> Int -> Int -> Int -> IO ()
printAns n k m m2 =
  putStrLn (foldl (\x y -> x ++ show k ++ " ") "" [1..m]
            ++ if m == n then "" else (show m2)
            ++ foldl (\x y -> x ++ " 0") "" [1..(n - m - 1)])

main = do
  line <- getLine
  let [n, k, t] = map (read::String->Int) (words line)
  let j = div (t * n * k) 100
  let m = div (t * n) 100
  let m2 = div (t * n * k - 100 * m * k) 100
  printAns n k m m2

-- Codeforces 71B

import Control.Applicative
import Data.List

main :: IO ()
main = do
    [n, k, t] <- (map read . words) <$> getLine :: IO [Int]
    let (u, v) = (t * (n * k) `div` 100) `divMod` k
        r = if u == n
               then replicate u k
               else replicate u k ++ [v] ++ replicate (n - u - 1) 0
    putStrLn $ intercalate " " (map show r)

main = do
	[n, k, t] <- (map read . words) `fmap` getLine
        let t' = toRational (t * n) / 100
            (чёрные, серость) = properFraction t'
            as = replicate чёрные k ++
                    replicate (ceiling серость) (floor (toRational k * серость)) ++
                    replicate (n - ceiling t') 0
	putStrLn $ unwords $ map show as

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

gen k t
	| t >= k = Just (show k,t-k)
	| t > 0 = Just (show t,0)
	| otherwise = Just (show 0,0)

main = do
	(sn:sk:st:_) <- words <$> getLine
	let n = read sn :: Int
	let k = read sk :: Int
	let t = read st :: Int
	putStr $ unwords $ take n $ unfoldr (gen k) $ truncate $ realToFrac (t*k*n)/100

module Main where

--import Debug.Trace

import Control.Monad
import Control.DeepSeq
import Data.Function
import Data.List
import Data.Char

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 = fmap head . sequence . map print
printStrs = fmap head . sequence . map putStrLn

process :: Int -> Int -> Int -> [Int]
process n k t = take n infBar where
    b = floor (fromIntegral (n * k * t) / 100)
    (q, r) = b `divMod` k
    infBar = replicate q k ++ [r] ++ repeat 0

main = do
    (n:k:[t]) <- getInts
    putStrLn . unwords . map show $ process n k t

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Main where
import Control.Applicative
import Data.List
import Text.Printf

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

g:: Int -> Int -> Int -> (Int,Int)
g n k t = (s,m)
    where n'  = (n*k*t `div` 100)
          s   = n' `div` k
          m   = n' `mod` k

floor' :: (Integral a) => a -> a
floor' = floor . fromIntegral

f n m s k = take n (l ++ [m] ++ r)
    where l = ((take (fromIntegral s)) . repeat $ k)
          m' = (if (length (l++r))>=n then [] else [m])
          r = repeat 0

main :: IO ()
main = do { n:k:t:_ <- map read . split . head . lines <$> getContents
          ; let (s,m) = g n k t in
            mapM_ (printf "%d ") $ f n m s k
          }

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Main where
import Control.Applicative
import Data.List
import Text.Printf

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

g:: Int -> Int -> Int -> (Int,Int)
g n k t = (s,m)
    where n'  = (n*k*t `div` 100)
          s   = n' `div` k
          m   = n' `mod` k

floor' :: (Integral a) => a -> a
floor' = floor . fromIntegral

f n m s k = l ++ m' ++ r
    where l = ((take (fromIntegral s)) . repeat $ k)
          m' = (if (length (l++r))>=n then [] else [m])
          r = (take (n-(fromIntegral s) - 1) . repeat $ 0)

main :: IO ()
main = do { n:k:t:_ <- map read . split . head . lines <$> getContents
          ; let (s,m) = g n k t in
            mapM_ (printf "%d ") $ f n m s k
          }

-- Codeforces 71B

import Control.Applicative
import Data.List

main :: IO ()
main = do
    [n, k, t] <- (map read . words) <$> getLine :: IO [Int]
    let (u, v) = (t * (n * k) `div` 100) `divMod` k
        r = if u == n
               then replicate u k
               else replicate u k ++ [v] ++ replicate (n - u - 1) 0
    print (u, v)
    putStrLn $ intercalate " " (map show r)

-- Codeforces 71B

import Control.Applicative
import Data.List

main :: IO ()
main = do
    [n, k, t] <- (map read . words) <$> getLine :: IO [Int]
    let (u, v) = (t * (n * k) `div` 100) `divMod` k
        r = replicate u k ++ [v] ++ replicate (n - u - 1) 0
    putStrLn $ intercalate " " (map show r)

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

import Data.Char
import Data.List
import qualified Data.Map as M
-- import Data.Map ((!))
import qualified Data.IntMap as IM
-- import Data.IntMap ((!))

import Data.Array
import Data.Function

import Debug.Trace

import Numeric

debug = flip trace
-- debug = const

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

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

double :: IO Double
double = read <$> getLine

doubles :: IO [Double]
doubles = map read . words <$> getLine

sum' = foldl' (+) 0
product' = foldl' (*) 1

fi = fromIntegral

calc :: Double -> Double -> Double -> (Int, Int)
calc n k t =
  let i = floor (n*t/100) + 1
      ai = floor (n*k*t/100 - (fi i - 1) * k)
  in (i, ai)

makeBar :: Double -> Double -> Int -> Int -> String
makeBar n k i ai =
  unwords . map show $ values
  where
    values :: [Int]
    values = replicate (i - 1) (round k) ++ [ai] ++ replicate (round n - i) 0

main = do
  [n, k, t] <- doubles
  let (i, ai) = calc n k t
  putStrLn $ makeBar n k i ai

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

import Data.Char
import Data.List
import qualified Data.Map as M
-- import Data.Map ((!))
import qualified Data.IntMap as IM
-- import Data.IntMap ((!))

import Data.Array
import Data.Function

import Debug.Trace

import Numeric

debug = flip trace
-- debug = const

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

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

double :: IO Double
double = read <$> getLine

doubles :: IO [Double]
doubles = read <$> getLine

sum' = foldl' (+) 0
product' = foldl' (*) 1

fi = fromIntegral

progressbar :: Int -> Int -> Int -> [Int]
progressbar n k t =
  let t' = fi t
      n' = fi n
      k' = fi k
      sigai = n' * k' * t' / 100
      (nSats, rem) = floor sigai `divMod` k
  in  replicate nSats k ++ [rem] ++ replicate (n - nSats - 1) 0

main = do
  [n, k, t] <- ints
  let res = progressbar n k t
  putStrLn (unwords (map show res))

main = do
	[n, k, t] <- (map read . words) `fmap` getLine
	let tnk = t * n * k
	    f s | (s + k) * 100 < tnk = k
		| s * 100 <= tnk && (s + k) * 100 > tnk = (tnk - s * 100) `div` 100
		| otherwise = 0
	let as = reverse $ snd $ foldl (\(s, as) _ -> (s + f s, f s:as)) (0, []) [1..n]
	putStrLn $ unwords $ map show as

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Main where
import Control.Applicative
import Data.List
import Text.Printf

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

g:: Int -> Int -> Int -> (Int,Int)
g n k t = (s,m)
    where n'  = (n*k*t `div` 100)
          s   = n' `div` k
          m   = n' `mod` k

floor' :: (Integral a) => a -> a
floor' = floor . fromIntegral

f n m s k = ((take (fromIntegral s)) . repeat $ k) ++ [m] ++ (take (n-(fromIntegral s) - 1) . repeat $ 0)

main :: IO ()
main = do { n:k:t:_ <- map read . split . head . lines <$> getContents
          ; let (s,m) = g n k t in
            mapM_ (printf "%d ") $ f n m s k
          }

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Main where
import Control.Applicative
import Data.List
import Text.Printf

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

g:: Int -> Int -> Int -> (Int,Int)
g n k t = (s,m)
    where n'  = (n*k*t `div` 100)
          s   = n' `div` k
          m   = n' `mod` k

floor' :: (Integral a) => a -> a
floor' = floor . fromIntegral

f n m s k = take n (l ++ [m] ++ [0..])
    where l = ((take (fromIntegral s)) . repeat $ k)
          m' = (if (length (l++r))>=n then [] else [m])
          r = repeat 0

main :: IO ()
main = do { n:k:t:_ <- map read . split . head . lines <$> getContents
          ; let (s,m) = g n k t in
            mapM_ (printf "%d ") $ f n m s k
          }

main=getLine>>=putStrLn.unwords.slv.map read.words
slv :: [Int] -> [String]
slv (n:k:t:_) =
    map show $ replicate nFull k ++ [v] ++ replicate (n - nFull - 1) 0
    where
        nFull = p `div` k
        v = p `mod` k
        p = floor $ (fromIntegral k)*(fromIntegral n)*(fromIntegral t) / 100


import Data.List
main=do
 (_:a)<-fmap (map read . words) getContents::IO [Int]
 let m=length [(x,y)|(x:ys)<-tails a,y<-ys,x>y]
 print $ (div m 2)*3+(m-(div m 2))

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

main = do
    n <- readLn
    ps <- readsLine
    print $ solve n ps

reverseNumber ps = length $ do
    (i,pi) <- zip [1..] ps
    pj     <- drop i ps
    guard $ pi > pj
    return ()

solve :: Int -> [Int] -> Int
solve n ps | even k     = 2*k
           | otherwise = 2*(k-1) + 1
    where
    k = reverseNumber ps

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

main = do
    n <- readLn
    ps <- readsLine
    print $ solve n ps

reverseNumber ps = length $ do
    (i,pi) <- zip [1..] ps
    pj     <- drop i ps
    guard $ pi > pj
    return ()

solve :: Int -> [Int] -> Int
solve n ps | k == 0    = 0
           | otherwise = 2*(k-1) + 1
    where
    k = reverseNumber ps


main = do
  (n:as) <- fmap (map read . words) getContents
  let counted = count as
  putStrLn $ if ((all (== head counted)) counted) then "YES" else "NO"
  return ()

count :: [Int] -> [Int]
count (a:as) = count' a as where
    count' a [] = [1]
    count' a (b:bs) = if a == b
        then
            let d:ds = count' b bs in (d+1):ds
        else
            1 : count' b bs

wordsWhen :: (Char -> Bool) -> String -> [String]
wordsWhen p s = case dropWhile p s of
    [] -> []
    s' -> w : wordsWhen p s''
        where (w, s'') = break p s'

ce :: (String -> Bool) -> [String] -> (Integer, [String])
ce _ [] = (0, [])
ce p (x:xs) = case p x of
    True -> (1 + fst r, snd r)
        where r = ce p xs
    False -> (0, x:xs)

change :: [String] -> [Integer]
change [] = []
change (x:xs) = fst r : change (snd r)
    where r = ce (== x) (x:xs)

isPossible :: [Integer] -> Bool
isPossible [] = True
isPossible (x:[]) = True
isPossible (x:x':xs) = (x == x') && (isPossible (x':xs))

makeString :: Bool -> String
makeString True = "YES"
makeString False = "NO"

solve :: String -> String
solve str = makeString $ isPossible $ change $ words sec
    where (_:sec:_) = lines str

main = interact solve

main = f

f = do
 n <- getLine
 --let x = read n :: Int
 img <- getLine
 let pixels = words img
 let first = head pixels
 putStrLn $ if check (words img) first then "YES" else "NO"

check l curr = check_rec l curr 0

check_rec [] _ _ = True

check_rec l curr 0 =
    let len = length $ takeWhile (\x -> x == curr) l in
     check_rec (drop len l) (changeSymbol curr) len

check_rec l curr n =
 let len = length $ takeWhile (\x -> x == curr) l in
  if len /= n then False else check_rec (drop len l) (changeSymbol curr) n

changeSymbol "1" = "0"
changeSymbol "0" = "1"

-- |inputs: (x:xs) is the photo
-- width is the width of the first stripe, or 0 if yet unknown
-- val is the colour of the current stripe
-- acc is the width of the current stripe
solve_rec :: [Int] -> Int -> Int -> Int -> String
solve_rec [] width _ acc
    | width == 0   = "YES"
    | width == acc = "YES"
    | otherwise    = "NO"
solve_rec (x:xs) width val acc
    | width == 0 =
        if val == x then solve_rec xs width x (acc + 1)
        else             solve_rec xs acc   x 1
    | width > acc =
        if val == x then solve_rec xs width x (acc + 1)
        else             "NO"
    | otherwise =
        if val == x then "NO"
        else             solve_rec xs width x 1

-- wrapper function to call recursive helper
solve :: [Int] -> String
solve (x:xs) = solve_rec (x:xs) 0 x 0

-- ignore first line and read second line as [Int]
main = do
    _ <- getLine
    s <- getLine
    -- must use putStrLn because print outputs quotation marks
    putStrLn $ solve $ map read $ words s

read_array :: String -> [Int]
read_array = map read . words

get_width :: [Int] -> Int -> Int -> Int
get_width [] _ acc = acc
get_width (x:xs) val acc
    | x == val   = get_width xs val (acc + 1)
    | otherwise  = acc

solve_rec :: [Int] -> Int -> Int -> Int -> String
solve_rec [] width _ acc
    | acc == width = "YES"
    | otherwise    = "NO"
solve_rec (x:xs) width val acc
    | x == val && acc < width  = solve_rec xs width val (acc + 1)
    | x == val && acc >= width = "NO"
    | x /= val && acc < width  = "NO"
    | 1 == val && acc >= width = solve_rec xs width 0 1
    | 0 == val && acc >= width = solve_rec xs width 1 1

solve :: [Int] -> String
solve [] = "YES"
solve (x:xs) = solve_rec (x:xs) (get_width (x:xs) x 0) x 0

solves :: [Int] -> Int
solves (x:xs) = get_width (x:xs) x 0

main = do
    n <- read `fmap` getLine :: IO Int
    s <- getLine :: IO String
    putStrLn (solve (read_array s))

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

conv ans cnt last [] = cnt:ans
conv ans cnt last (x:xs) =
    if last == x
       then conv ans (cnt + 1) last xs
       else conv (cnt:ans) 1 x xs

allTheSame xs = and $ map (== head xs) (tail xs)

solve (x:xs) =
    if allTheSame (conv [] 1 x xs)
       then "YES"
       else "NO"

main = do
    n <- getLine
    a <- getInts
    putStrLn $ solve a

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

process0 :: Int -> [Int] -> (Int,[Int])
process0 x [] = (0,[])
process0 x (y:as) = if x==y then (1 + (fst d),(snd d)) else (0,(y:as))
    where d = process0 x as

process :: [Int] -> [Int]
process [] = []
process (x:as) = ((fst d):(process (snd d)))
    where d = (process0 x (x:as))

main :: IO()
main = do
    s <- getLine
    let x = (read s :: Int)
    a <- readInts
    let b = process a
    let t = and $ map (== head b) (tail b)
    let ans = if t then "YES" else "NO"
    putStrLn ans

read_array :: String -> [Int]
read_array = map read . words

get_width :: [Int] -> Int -> Int -> Int
get_width [] _ acc = acc
get_width (x:xs) val acc
    | x == val   = get_width xs val (acc + 1)
    | otherwise  = acc

solve_rec :: [Int] -> Int -> Int -> Int -> String
solve_rec [] _ _ _ = "YES"
solve_rec (x:xs) width val acc
    | x == val && acc < width  = solve_rec xs width val (acc + 1)
    | x == val && acc >= width = "NO"
    | x /= val && acc < width  = "NO"
    | 1 == val && acc >= width = solve_rec xs width 0 1
    | 0 == val && acc >= width = solve_rec xs width 1 1

solve :: [Int] -> String
solve [] = "YES"
solve (x:xs) = solve_rec (x:xs) (get_width (x:xs) x 0) x 0

solves :: [Int] -> Int
solves (x:xs) = get_width (x:xs) x 0

main = do
    n <- read `fmap` getLine :: IO Int
    s <- getLine :: IO String
    print (solve (read_array s))

read_array :: String -> [Int]
read_array = map read . words

get_width :: [Int] -> Int -> Int -> Int
get_width [] _ acc = acc
get_width (x:xs) val acc
    | x == val   = get_width xs val (acc + 1)
    | otherwise  = acc

solve_rec :: [Int] -> Int -> Int -> Int -> String
solve_rec [] _ _ _ = "YES"
solve_rec (x:xs) width val acc
    | x == val && acc < width  = solve_rec xs width val (acc + 1)
    | x == val && acc >= width = "NO"
    | x /= val && acc < width  = "NO"
    | 1 == val && acc >= width = solve_rec xs width 0 1
    | 0 == val && acc >= width = solve_rec xs width 1 1

solve :: [Int] -> String
solve [] = "YES"
solve (x:xs) = solve_rec (x:xs) (get_width (x:xs) x 0) x 0

solves :: [Int] -> Int
solves (x:xs) = get_width (x:xs) x 0

main = do
    n <- read `fmap` getLine :: IO Int
    s <- getLine :: IO String
    putStrLn (solve (read_array s))

read_array :: String -> [Int]
read_array = map read . words

get_width :: [Int] -> Int -> Int -> Int
get_width [] _ acc = acc
get_width (x:xs) val acc
    | x == val   = get_width xs val (acc + 1)
    | otherwise  = acc

solve_rec :: [Int] -> Int -> Int -> Int -> String
solve_rec [] _ val acc
    | val == acc = "YES"
    | otherwise  = "NO"
solve_rec (x:xs) width val acc
    | x == val && acc < width  = solve_rec xs width val (acc + 1)
    | x == val && acc >= width = "NO"
    | x /= val && acc < width  = "NO"
    | 1 == val && acc >= width = solve_rec xs width 0 1
    | 0 == val && acc >= width = solve_rec xs width 1 1

solve :: [Int] -> String
solve [] = "YES"
solve (x:xs) = solve_rec (x:xs) (get_width (x:xs) x 0) x 0

solves :: [Int] -> Int
solves (x:xs) = get_width (x:xs) x 0

main = do
    n <- read `fmap` getLine :: IO Int
    s <- getLine :: IO String
    putStrLn (solve (read_array s))


import Control.Monad (liftM)
import Data.Char (ord)
import Data.List (sort)
import Prelude hiding (reads)

reads :: IO [Integer]
reads  =  liftM (map read . words) getLine
  where
    read ('-' : s)  =  (-1) * read s
    read s  =  read' 0 s
    read' a ""  =  a
    read' a (c:s)  =  read' a' s
      where
        a'  =  10*a + fromIntegral (ord c - ord '0')

solve :: Integer -> Integer -> [Integer] -> (Integer, Integer)
solve n k as  =  (a, b)
  where
    indexA  =  fromIntegral ((k-1) `div` n) + 1
    countA  =  fromIntegral $ length $ filter (== a) as
    countLessA  =  length $ filter (< a) as
    indexInGroup  =  k - n * fromIntegral countLessA
    indexB  =  fromIntegral ((indexInGroup - 1) `div` countA) + 1
    a  =  sort as !! (indexA - 1)
    b  =  sort as !! (indexB - 1)

test :: [Integer] -> IO ()
test as  =  do
    let n  =  fromIntegral $ length as
    let ans1  =  sort [(a, b) | a <- as, b <- as]
    let ans2  =  map (\k -> solve n k as) [1..n*n]
    if ans1 == ans2 then
        print "Ok"
    else
        print "Fail: " >> print as

main :: IO ()
main  =  do
    [n, k]  <-  reads
    as  <-  reads
    let (a, b)  =  solve n k as
    putStrLn $ concat [show a, " ", show b]

import Control.Applicative
import Data.List
import qualified Data.ByteString.Char8 as BS

solve :: [Int] -> Integer -> Integer -> (Int, Int)
solve a k n = solve' a k
    where
      solve' (x:xs) k = let cnt = fromIntegral $ length $ takeWhile (== x) (x:xs) :: Integer
                            all = cnt * n
                        in if all > k
                           then (x, a !! (fromIntegral (k `div` cnt)))
                           else solve' (dropWhile (== x) xs) (k - all)

main = do
  [n, k] <- (map (toNumber . BS.readInteger) <$> (BS.words <$> BS.getLine)) :: IO [Integer]
  a      <- (sort <$> map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
  let (f, s) = solve a (k - 1) n
  putStrLn $ (show f) ++ " " ++ (show s)

toNumber :: Num a => Maybe (a, BS.ByteString) -> a
toNumber (Just (x, _)) = x
toNumber Nothing       = 0

import Control.Applicative
import Data.List

main = do
  [n, k] <- (map read <$> (words <$> getLine)) :: IO [Integer]
  a      <- (sort <$> map read <$> (words <$> getLine)) :: IO [Int]
  putStrLn $ (show $ a !! (fromIntegral ((k - 1) `div` n))) ++ " " ++ (show $ a !! (fromIntegral ((k - 1) `mod` n)))

import Control.Applicative
import Data.List

main = do
  [n, k] <- (map read <$> (words <$> getLine)) :: IO [Integer]
  a      <- (sort <$> map read <$> (words <$> getLine)) :: IO [Integer]
  putStrLn $ (show $ a !! (fromIntegral ((k - 1) `div` n))) ++ " " ++ (show $ a !! (fromIntegral ((k - 1) `mod` n)))

import Data.List

getWords :: IO [String]
getWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = getWords >>= return . (map read)

solve :: (Int, Int) -> [Int] -> (Int, Int)
solve (n, k) xs  =  (x', sortXs !! (y `div` z))
  where
    sortXs  =  sort xs
    (x, y)  =  (k-1) `divMod` n
    x'  =  sortXs !! x
    z  =  length $ filter (== x') sortXs

main :: IO ()
main  =  do
    [n, k] <- Main.reads
    xs <- Main.reads
    let (x, y)  =  solve (n, k) xs
    putStrLn $ concat [show x, " ", show y]

import List

getWords :: IO [String]
getWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = getWords >>= return . (map read)

solve :: (Int, Int) -> [Int] -> (Int, Int)
solve (n, k) xs  =  (sortXs !! x, sortXs !! y)
  where
    sortXs  =  sort xs
    (x, y)  =  (k-1) `divMod` n

main :: IO ()
main  =  do
    [n, k] <- Main.reads
    xs <- Main.reads
    let (x, y)  =  solve (n, k) xs
    putStrLn $ concat [show x, " ", show y]

import Control.Monad (liftM)
import Data.List (sort)
import Prelude hiding (print, reads)

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: Integer -> Integer -> [Int] -> (Int, Int)
solve n k xs  =  (xs' !! a, xs' !! b)
  where
    a    =  fromIntegral $ div (k-1) n
    b    =  fromIntegral $ mod (k-1) n
    xs'  =  sort xs

print :: (Int, Int) -> IO ()
print (a, b)  =  putStrLn $ concat [show a, " ", show b]

main :: IO ()
main  =  do
    [n, k]  <-  reads
    xs      <-  reads
    print $ solve n k xs

import Data.List

getWords :: IO [String]
getWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = getWords >>= return . (map read)

solve :: (Integer, Integer) -> [Int] -> (Int, Int)
solve (n, k) xs  =  (x', sortXs !! ((fromIntegral y) `div` z))
  where
    sortXs  =  sort xs
    (x, y)  =  (k-1) `divMod` n
    x'  =  sortXs !! (fromIntegral x)
    z  =  length $ filter (== x') sortXs

main :: IO ()
main  =  do
    [n, k] <- Main.reads
    xs <- Main.reads
    let (x, y)  =  solve (n, k) xs
    putStrLn $ concat [show x, " ", show y]

import Control.Monad (liftM)
import Data.Char (ord)
import Data.List (sort)
import Prelude hiding (reads)

reads :: IO [Integer]
reads  =  liftM (map read . words) getLine
  where
    read ('-' : s)  =  (-1) * read s
    read s  =  read' 0 s
    read' a ""  =  fromIntegral a
    read' a (c:s)  =  read' (10*a + ord c - ord '0') s

solve :: Integer -> Integer -> [Integer] -> (Integer, Integer)
solve n k as  =  (a, b)
  where
    indexA  =  fromIntegral ((k-1) `div` n) + 1
    countA  =  fromIntegral $ length $ filter (== a) as
    countLessA  =  length $ filter (< a) as
    indexInGroup  =  k - n * fromIntegral countLessA
    indexB  =  fromIntegral ((indexInGroup - 1) `div` countA) + 1
    a  =  sort as !! (indexA - 1)
    b  =  sort as !! (indexB - 1)

test :: [Integer] -> IO ()
test as  =  do
    let n  =  fromIntegral $ length as
    let ans1  =  sort [(a, b) | a <- as, b <- as]
    let ans2  =  map (\k -> solve n k as) [1..n*n]
    if ans1 == ans2 then
        print "Ok"
    else
        print "Fail: " >> print as

main :: IO ()
main  =  do
    [n, k]  <-  reads
    as  <-  reads
    let (a, b)  =  solve n k as
    putStrLn $ concat [show a, " ", show b]


readInteger :: String -> Integer
readInteger token = read token :: Integer

unchargedSlot = "."
chargedSlot = "X"

toList :: a -> [a]
toList item = [item]

processQuery :: Integer -> Integer -> Integer -> Integer -> String
processQuery u v n x = if 0 <= x && x < n - t then
                         unchargedSlot
                       else if n - t <= x && x < n - v then
                              if even (x - n + t) then
                                unchargedSlot
                                else
                                chargedSlot
                            else
                              chargedSlot
  where t = 2 * u + v

solve :: [Integer] -> [String]
solve (n:k:p:queries) | odd (n - 2 * u - v) = map (processQuery (u - 1) (v + 1) n) q
                      | otherwise = map (processQuery u v n) q
  where u = min k (n - k)
        v = k - u
        q = map pred queries

main :: IO ()
main = interact (unlines . toList . foldl (++) "" . solve . map readInteger . words)

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

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

import Debug.Trace

parseInput = do
    n <- readInteger
    k <- readInteger
    p <- readInt
    query <- replicateM p readInteger
    return (n, k, query)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

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

solve (n, k, query) = map solvePosition query
  where
    solvePosition x
        | k == 0    = '.'
        | k == n    = 'X'
        | k == 1    = if x == n then 'X' else '.'
        | partLeft  = if x == left then 'X' else '.'
        | partA     = if (x - left) `mod` 2 == 0 then 'X' else '.'
        | otherwise = 'X'
      where
        partLeft = x <= left
        partA = (x - left) <= 2 * a

    minB = n `mod` 2

    -- 2 * a + b <= n - 2
    -- a + b + 1 == k

    a = ((n - 2) - (k - 1)) `min` (k - 1 - minB)
    b = k - 1 - a

    left = n - 2 * a - b

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

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

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

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

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

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

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

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

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

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

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

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

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

state = State

module Main where

import Control.Monad

main = do
    [n, k, p] <- ( map read . words ) `liftM` getLine :: IO [Integer]

    q <- replicateM (fromIntegral p) $ read `liftM` getLine
    let hn = ( n + 1 ) `div` 2

    putStrLn $ map (\q -> let hq = q `div` 2 in if q `mod` 2 == 0
        then if hq + k > hn then 'X' else '.'
        else if k > 0 && q == n || hq + k >= n then 'X' else '.'
        ) q

module Main where

import Control.Monad

main = do
    [n, k, p] <- ( map read . words ) `liftM` getLine

    q <- replicateM p $ read `liftM` getLine
    let hn = ( n + 1 ) `div` 2

    putStrLn $ map (\q -> let hq = q `div` 2 in if q `mod` 2 == 0
        then if hq + k > hn then 'X' else '.'
        else if q == n || hq + k >= n then 'X' else '.'
        ) q

module Main where

import Control.Monad

main = do
    [n, k, p] <- ( map read . words ) `liftM` getLine

    q <- replicateM n $ read `liftM` getLine
    let hn = ( n + 1 ) `div` 2

    putStrLn $ map (\q -> let hq = q `div` 2 in if q `mod` 2 == 0
        then if hq + k > hn then 'X' else '.'
        else if q == n || hq + k >= n then 'X' else '.'
        ) q

module Main where

import Control.Monad

main = do
    [n, k, p] <- ( map read . words ) `liftM` getLine :: IO [Integer]

    q <- replicateM (fromIntegral p) $ read `liftM` getLine
    let hn = ( n + 1 ) `div` 2

    putStrLn $ map (\q -> let hq = q `div` 2 in if q `mod` 2 == 0
        then if hq + k > hn then 'X' else '.'
        else if q == n || hq + k >= n then 'X' else '.'
        ) q

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

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

import Debug.Trace

parseInput = do
    n <- readInteger
    k <- readInteger
    p <- readInt
    query <- replicateM p readInteger
    return (n, k, query)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

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

solve (n, k, query) = map solvePosition query
  where
    solvePosition x
        | k == 0    = '.'
        | k == n    = 'X'
        | partLeft  = if x == left then 'X' else '.'
        | partA     = if (x - left) `mod` 2 == 0 then 'X' else '.'
        | otherwise = 'X'
      where
        partLeft = x <= left
        partA = (x - left) <= 2 * a

    minB = n `mod` 2

    -- 2 * a + b <= n - 2
    -- a + b + 1 == k

    a = ((n - 2) - (k - 1)) `min` (k - 1 - minB)
    b = k - 1 - a

    left = n - 2 * a - b

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

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

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

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

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

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

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

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

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

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

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

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

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

state = State


module Main where

import Data.List
import Control.Exception

scanPairs :: [a] -> [(a, a)]
scanPairs xs = zip xs $ tail xs

chunks :: Int -> [a] -> [[a]]
chunks _ [] = []
chunks n xs = take n xs : chunks n (drop n xs)

solveCase :: String -> String
solveCase =
  show .
  sum .
  map (\(x, y) -> assert (x <= y) $ y - x - 1) .
  scanPairs .
  map fst .
  filter ((==) "1" . snd) .
  zip [0..] .
  words

main :: IO ()
main = interact $ unlines . map solveCase . concatMap tail . chunks 2 . tail . lines

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
import safe Data.List (dropWhileEnd)

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

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

solve :: [Char] -> Int
solve = length . filter (== '0') . dropWhileEnd (/= '1') . dropWhile (/= '1')

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    _ <- getInts
    as <- getInts
    putStrLn $ show $ length $ filter (==0) $ dropWhile (==0) $ reverse $ dropWhile (==0) as

import           Data.List (dropWhileEnd)

everyOther :: [a] -> [a]
everyOther []       = []
everyOther (x:y:xs) = y : everyOther xs

countMoves :: String -> String
countMoves s = show $ foldr countZeros 0 (stripZeros (words s))
  where
    stripZeros = dropWhileEnd (== "0") . dropWhile (== "0")
    countZeros x acc = if x == "0" then acc + 1 else acc

main :: IO ()
main = do
    _ <- getLine
    interact $ unlines . map countMoves . everyOther . lines

import Control.Monad

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

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _n <- getLine
    a <- readInts
    let
      a1 = dropWhile (== 0) a
      a2 = dropWhile (== 0) $ reverse a1
    print $ length [() | x <- a2, x == 0]

import Control.Monad

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

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

main :: IO ()
main = do
    t <- readInt
    replicateM_ t $ do
        n <- readInt
        let m = n + 1
        a <- readInts
        let a' = trimZeroes a in putStrLn $ show $ (length a') - (sum a')

trimZeroes::[Int] -> [Int]
trimZeroes = f . f
            where f = reverse . dropWhile (== 0)


import Control.Applicative ((<$>))
import Data.List ((\\))
import Data.Maybe (fromJust)
import Data.Tuple (fst, uncurry)

main = do
	getLine
	sizes <- map ((\[w, h] -> (w, h)) . map read . words) . lines <$> getContents

	let solution =
			map (uncurry solve) sizes
		where
			(ws, hs) = unzip sizes
			totalWeight = sum ws
			h1 = maximum hs
			h2 = maximum $ hs \\ [h1]

			solve w h = (totalWeight - w) * (if h == h1 then h2 else h1)

	putStrLn . unwords $ map show solution

{-# LANGUAGE MultiWayIf #-}
import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  n <- readInt <$> C.getLine
  a <- replicateM n $ do
    [w, h] <- map readInt . C.words <$> C.getLine
    return (w, h)
  let (h1, h2) = flip foldl1' ((0, 0): a) $ \k@(i, j) (_, h) -> if
        | h > i -> (h, i)
        | h > j -> (i, h)
        | otherwise -> k
      sw = sum $ map fst a
      ans = [(sw - w) * (if h /= h1 then h1 else h2) | (w, h) <- a]
  putStrLn $ unwords $ map show ans
  where
  readInt = fst . fromJust . C.readInt

import Data.List

ans :: [(Int,Int)] -> [Int]
ans ls = map (\(x,y) -> (sumFstLs - x)*(if y == maxi then maxi2 else maxi)) ls where
	sumFstLs	= sum (map fst ls)
	sortedSndLs	= reverse $ sort (map snd ls)
	maxi 		= sortedSndLs !! 0
	maxi2		= sortedSndLs !! 1

getPairs :: 		[Int] -> [(Int,Int)]
getPairs [] 		= []
getPairs (x:y:xs) 	= (x,y):(getPairs xs)

main :: IO()
main = do
	n <- getLine
	content <- fmap (map read . words) getContents
	putStrLn $ intercalate " " $ map show $ ans $ getPairs content

import Control.Applicative ((<$>))
import Data.List ((\\))

main = do
	getLine
	sizes <- map ((\[w, h] -> (w, h)) . map read . words) . lines <$> getContents

	let solution =
			map (uncurry solve) sizes
		where
			solve w h =
					(s - w) * (if h == h1 then h2 else h1)
				where
					(ws, hs) = unzip sizes
					s = sum ws
					h1 = maximum hs
					h2 = maximum $ hs \\ [h1]

	putStrLn . unwords $ map show solution

{-# OPTIONS_GHC -O3 #-}

import Control.Applicative ((<$>))
import Data.ByteString (getContents, getLine)
import Data.ByteString.Char8 (readInt, lines, words)
import Data.List ((\\))
import Data.Maybe (fromJust)
import Data.Tuple (fst, uncurry)

import Prelude hiding (getContents, getLine, lines, words)

main = do
	getLine
	sizes <- map ((\[w, h] -> (w, h)) . map (fst . fromJust . readInt) . words) . lines <$> getContents

	let solution =
			map (uncurry solve) sizes
		where
			solve w h =
					(s - w) * (if h == h1 then h2 else h1)
				where
					(ws, hs) = unzip sizes
					s = sum ws
					h1 = maximum hs
					h2 = maximum $ hs \\ [h1]

	putStrLn . unwords $ map show solution

{-# OPTIONS_GHC -O2 #-}

import Control.Applicative ((<$>))
import Data.ByteString (getContents, getLine)
import Data.ByteString.Char8 (readInt, lines, words)
import Data.List ((\\))
import Data.Maybe (fromJust)
import Data.Tuple (fst, uncurry)

import Prelude hiding (getContents, getLine, lines, words)

main = do
	getLine
	sizes <- map ((\[w, h] -> (w, h)) . map (fst . fromJust . readInt) . words) . lines <$> getContents

	let solution =
			map (uncurry solve) sizes
		where
			solve w h =
					(s - w) * (if h == h1 then h2 else h1)
				where
					(ws, hs) = unzip sizes
					s = sum ws
					h1 = maximum hs
					h2 = maximum $ hs \\ [h1]

	putStrLn . unwords $ map show solution

import Control.Applicative ((<$>))
import Data.List ((\\))
import Data.Maybe (fromJust)
import Data.Tuple (fst, uncurry)

main = do
	getLine
	sizes <- map ((\[w, h] -> (w, h)) . map read . words) . lines <$> getContents

	let solution =
			map (uncurry solve) sizes
		where
			(ws, hs) = unzip sizes
			-- totalWeight = sum ws
			h1 = maximum hs
			h2 = maximum $ hs \\ [h1]

			solve w h = (s - w) * (if h == h1 then h2 else h1)
				where
					s = sum ws

	putStrLn . unwords $ map show solution

import Control.Applicative ((<$>))
import Data.ByteString (getContents, getLine)
import Data.ByteString.Char8 (readInt, lines, words)
import Data.List ((\\))
import Data.Maybe (fromJust)
import Data.Tuple (fst, uncurry)

import Prelude hiding (getContents, getLine, lines, words)

main = do
	getLine
	sizes <- map ((\[w, h] -> (w, h)) . map (fst . fromJust . readInt) . words) . lines <$> getContents

	let solution =
			map (uncurry solve) sizes
		where
			(ws, hs) = unzip sizes
			totalWeight = sum ws
			h1 = maximum hs
			h2 = maximum $ hs \\ [h1]

			solve w h = (totalWeight - w) * (if h == h1 then h2 else h1)

	putStrLn . unwords $ map show solution

readInput = do
    contents <- getContents
    let [n] : _sizes = map (map (read :: String -> Int) . words) $ lines contents
    let sizes = map (\[w, h] -> (w, h)) _sizes
    return (n, sizes)

printResult result = putStr $ unwords $ map show result

addMax (a, b) x
    | x > a     = (x, a)
    | x > b     = (a, x)
    | otherwise = (a, b)

remMax (a, b) x
    | x == a    = b
    | otherwise = a

getMax2 arr = foldl addMax (minVal, minVal) arr
    where minVal = -1

solve sizes = map f sizes
    where sumv     = sum $ map fst sizes
          max2     = getMax2 $ map snd sizes
          f (w, h) = (sumv - w) * (remMax max2 h)

main = do
    (n, sizes) <- readInput
    printResult $ solve sizes

import Control.Monad
secondMaximum l = if length lAlt == n - 1 then maximum lAlt else mx
    where
      mx = maximum l
      lAlt = filter (/= mx) l
      n = length l
solve l =
    map (\(w, h)-> (totalWidth - w) * (alternative h firstH secondH)) l
    where
      totalWidth = sum $ map fst l :: Integer
      firstH = maximum $ map snd l
      secondH = secondMaximum $ map snd l
      alternative x y z = if x == y then z else y :: Integer

main = do
  n <- liftM read getLine
  l <- forM [1..n] (\ i -> liftM (listToPair . map read . words) getLine)
  putStrLn $ unwords $ map show $ solve l
  where
    listToPair [a, b] = (a, b)

import Data.List

ans :: [(Int,Int)] -> [Int]
ans ls = map (\(x,y) -> (sumFstLs - x)*(if y == maxi then maxi2 else maxi)) ls where
	sumFstLs	= sum (map fst ls)
	sortedSndLs	= reverse $ sort (map snd ls)
	maxi 		= sortedSndLs !! 0
	maxi2		= sortedSndLs !! 1

getPairs :: 		[Int] -> [(Int,Int)]
getPairs [] 		= []
getPairs (x:y:xs) 	= (x,x):(getPairs xs)

main :: IO()
main = do
	n <- getLine
	content <- fmap (map read . words) getContents
	putStrLn $ intercalate " " $ map show $ ans $ getPairs content


import Data.List ( sort )

solve :: [Integer] -> String
solve [x, y, z]
  | y == z    = "YES\n" ++ unwords (map show [x, x, z])
  | otherwise = "NO"

main :: IO ()
main = interact $ unlines . map (solve . sort . map read . words) . tail . lines

import Data.List

main = do
    contents <- getContents
    let notnull = filter (not . null) $ lines contents
    mapM solve $ drop 1 $ map (sort . map (read :: String -> Int) . words) notnull

solve (a:b:c:[])
    | b == c = putStrLn ("YES " ++ show b ++ " " ++ show a ++ " 1")
    | otherwise = putStrLn "NO"

module Main where
import Data.List
main :: IO ()
main = interact $ unlines . map solve . tail . lines

solve :: String -> String
solve str=
  let
      (x:y:z:[]) = sort $ map read $ words str :: [Integer]
      b = x
      c = y
      a = if (c > b) then b - 1 else c - 1
  in
   if (z /= max b c)
   then "NO\n"
   else if (a == 0)
   then "YES\n" ++ show (a+1) ++ " " ++ show b ++ " " ++ show c
   else "YES\n" ++ show a ++ " " ++ show b ++ " " ++ show c

-- solve :: String -> String
-- solve str=
--   let
--       (x:y:z:[]) = map read $ words str :: [Integer]
--       l = [1 .. 1000]
--       ll = [(a, b, c) | a <- l, b <- l, c <-l, x == max a b, y == max a c, z == max b c]
--       (a, b, c) = if null ll then (0, 0, 0) else head ll
--   in
--    if (a == 0 || b == 0 || c == 0)
--    then "NO\n"
--    else "YES\n" ++ show a ++ " " ++ show b ++ " " ++ show c

-- max1 :: Integer -> Integer -> Maybe Integer
-- max1 a b = if a == b then Nothing else Just $ max a b

main = interact $ unlines . concat . map (solve . map show . sort . map read) . map words . tail . lines

solve :: [String] -> [String]
solve (x:y:z:_)
  | x == y && y == z = ["YES", unwords [x, x, x]]
  | x == y = ["YES", unwords [x, z, z]]
  | otherwise = ["NO"]

sort :: [Integer] -> [Integer]
sort (x:y:z:[])
  | x >= y && y >= z = [x, y, z]
  | x >= z && z >= y = [x, z, y]
  | y >= x && x >= z = [y, x, z]
  | y >= z && z >= x = [y, z, x]
  | z >= y && y >= x = [z, y, x]
  | z >= x && x >= y = [z, x, y]

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

solve :: [Integer] -> String
solve [x, y, z]
  | y == z    = "YES\n" ++ unwords (map show [x, x, z])
  | otherwise = "NO"

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n $ solve . sort . map read . words <$> getLine >>= putStrLn

module Main where

import Data.List
import Control.Monad (replicateM_)

go :: IO ()
go = do
  [x, y, z] <- reverse . sort . map read . words <$> getLine :: IO [Integer]
  if x == y && y == z
    then putStrLn "YES" >> putStrLn (unwords $ show <$> [x, y, z])
    else if x == y && y > z
      then putStrLn "YES" >> putStrLn (unwords $ show <$> [x, z, z])
      else putStrLn "NO"

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

import Control.Monad
import Data.List

solve :: [Int] -> [Int]
solve xs @ [x, y, z]
  | yes && x == y && y == z = [m, m, m]
  | yes = [m, z, z]
  | otherwise = []

  where
    yes = length (xs \\ [m, m]) == 1
    m = maximum xs
    z = minimum xs

print' :: [Int] -> IO ()
print' xs
  | null xs = putStrLn "NO"
  | otherwise = putStrLn "YES" >> putStrLn (unwords . map show $ xs)

test :: Int -> IO ()
test n = do
  tests <- replicateM n (map read . words <$> getLine)
  mapM_ (print' . solve) tests

main :: IO ()
main = do
  n <- getLine
  let n' = (read n :: Int)
  test n'

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

process x y z | x==y && y==z = [x,x,x]
	      | x==y = []
              | y==z = [x,x,y]
	      | otherwise = []

onecase = do
		[x,y,n]<- sort <$> map read <$> words <$> getLine ::IO [Int]
		let k = process x y n
		putStrLn $ if k==[] then "NO" else "YES"
		if k/=[] then putStrLn ( intercalate " " ( map show k)) else putStr ""

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

import Data.List

main = do
    contents <- getContents
    mapM solve (drop 1 (map (sort . words) (lines contents)))

solve (a:b:c:[])
    | b == c = putStrLn ("YES " ++ b ++ " " ++ a ++ " 1")
    | otherwise = putStrLn "NO"

module Main where

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

solve :: String -> String
solve str=
  let
      (x:y:z:[]) = map read $ words str :: [Integer]
      b = x
      c = y
      a = if (c > b) then b - 1 else c - 1
  in
   if (z /= max b c)
   then "NO\n"
   else "YES\n" ++ show a ++ " " ++ show b ++ " " ++ show c

-- solve :: String -> String
-- solve str=
--   let
--       (x:y:z:[]) = map read $ words str :: [Integer]
--       l = [1 .. 1000]
--       ll = [(a, b, c) | a <- l, b <- l, c <-l, x == max a b, y == max a c, z == max b c]
--       (a, b, c) = if null ll then (0, 0, 0) else head ll
--   in
--    if (a == 0 || b == 0 || c == 0)
--    then "NO\n"
--    else "YES\n" ++ show a ++ " " ++ show b ++ " " ++ show c

-- max1 :: Integer -> Integer -> Maybe Integer
-- max1 a b = if a == b then Nothing else Just $ max a b

module Main where

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

solve :: String -> String
solve str=
  let
      (x:y:z:[]) = map read $ words str :: [Integer]
      b = x
      c = y
      a = if (c > b) then b - 1 else c - 1
  in
   if (z /= max b c)
   then "NO\n"
   else if (a == 0)
   then "YES\n" ++ show (a+1) ++ " " ++ show b ++ " " ++ show c
   else "YES\n" ++ show a ++ " " ++ show b ++ " " ++ show c

-- solve :: String -> String
-- solve str=
--   let
--       (x:y:z:[]) = map read $ words str :: [Integer]
--       l = [1 .. 1000]
--       ll = [(a, b, c) | a <- l, b <- l, c <-l, x == max a b, y == max a c, z == max b c]
--       (a, b, c) = if null ll then (0, 0, 0) else head ll
--   in
--    if (a == 0 || b == 0 || c == 0)
--    then "NO\n"
--    else "YES\n" ++ show a ++ " " ++ show b ++ " " ++ show c

-- max1 :: Integer -> Integer -> Maybe Integer
-- max1 a b = if a == b then Nothing else Just $ max a b

import Control.Monad
import Data.List

solve :: [Int] -> [Int]
solve xs @ [x, y, z]
  | yes && x == y && y == z = [m, m, m]
  | yes = xs
  | otherwise = []

  where
    yes = length (xs \\ [m, m]) == 1
    m = maximum xs

print' :: [Int] -> IO ()
print' xs
  | null xs = putStrLn "NO"
  | otherwise = putStrLn "YES" >> putStrLn (unwords . map show $ xs)

test :: Int -> IO ()
test n = do
  tests <- replicateM n (map read . words <$> getLine)
  mapM_ (print' . solve) tests

main :: IO ()
main = do
  n <- getLine
  let n' = (read n :: Int)
  test n'


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Int
import Data.Ix
import qualified Data.IntMap as IM
import Data.List
import Data.Ord

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

unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main = do
  n <- readLn
  xs <- map readInt.B.words <$> B.getLine
  let (res, len, cut) = solve n $ map fromIntegral xs
  putStrLn $ shows res " " ++ show len
  putStrLn.unwords $ map show cut

solve :: Int -> [Int64] -> (Int64, Int, [Int])
solve n xs = (calc (l, r), k , cut)
   where
     (l, r) = snd $ maximum [(calc lr, lr) | lr <- findLRs 0 IM.empty $ map fromIntegral xs]
     cut = [1..l] ++ [i+1|i<-[l+1..r-1], unsafeAt arr i<0] ++ [r+2..n]
     k = length cut

     arr      = listArray (0,n-1) xs                            :: UArray Int Int64
     sumArray = listArray (0,n-1) $ scanl1 (+) $ map (max 0) xs :: UArray Int Int64

     findLRs !i !im (x:xs) = case IM.lookup x im of
                              Nothing      -> findLRs (i+1) (IM.insert x [i] im) xs
                              Just (l:_)   -> findLRs (i+1) (IM.insert x [l,i] im) xs
     findLRs !_ !im _ = [(l, r) | [l,r] <- IM.elems im]

     calc (l, r)
       | l+1 > r-1 = unsafeAt arr l + unsafeAt arr r
       | otherwise = unsafeAt arr l + unsafeAt arr r + unsafeAt sumArray (r-1)  - unsafeAt sumArray l

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import Data.Int
import Data.Ix
import qualified Data.IntMap as IM
import Data.List
import Data.Ord

unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

newtype BIT = BIT (UArray Int Int64)

query :: Int -> BIT -> Int64
query key (BIT bit) = go key 0
  where
    go !i !res
      | i >= 0 = go ((i .&. (i+1)) - 1) $ res + unsafeAt bit i
      | otherwise = res

main = do
  n <- readLn
  xs <- map read.words <$> getLine
  let (res, cut) = solve n xs
  putStrLn $ shows res " " ++ show (length cut)
  putStrLn.unwords $ map show cut

data LR = L {-# UNPACK #-} !Int
        | LR {-# UNPACK #-} !Int {-# UNPACK #-} !Int

solve :: Int -> [Int64] -> (Int64, [Int])
solve n xs = (calc (l,r), [1..l]++[i+1|i<-[l+1..r-1],unsafeAt arr i<0]++[r+2..n])
   where
     arr = listArray (0,n-1) xs :: UArray Int Int64

     bit = runST $ do
       bit <- newArray (0, n-1) 0 :: ST s (STUArray s Int Int64)
       let add key x = do
             let go !i = when (i < n) $ do
                   unsafeModify bit i (x+)
                   go $ i .|. (i + 1)
             when (x>0) $ go key
       let go !i (x:xs)=add i x>>go(i+1)xs
           go _ _ = return ()
       go 0 xs
       BIT <$> unsafeFreeze bit

     findLRs !i im (x:xs) = case IM.lookup x im of
                              Nothing       -> findLRs (i+1) (IM.insert x (L i) im) xs
                              Just (L l)    -> findLRs (i+1) (IM.insert x (LR l i) im) xs
                              Just (LR l _) -> findLRs (i+1) (IM.insert x (LR l i) im) xs
     findLRs _ im _ = [(l, r) | LR l r <- IM.elems im]

     calc (l, r)
       | l+1 > r-1 = unsafeAt arr l + unsafeAt arr r
       | otherwise = unsafeAt arr l + unsafeAt arr r + query (r-1) bit - query l bit

     (l, r) = maximumBy (comparing calc) $ findLRs 0 IM.empty $ map fromIntegral xs

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Int
import Data.Ix
import qualified Data.IntMap as IM
import Data.List
import Data.Ord

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

unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main = do
  n <- readLn
  xs <- map readInt.B.words <$> B.getLine
  let (res, len, cut) = solve n $ map fromIntegral xs
  putStrLn $ shows res " " ++ show len
  putStrLn.unwords $ map show cut

solve :: Int -> [Int64] -> (Int64, Int, [Int])
solve n xs = (calc (l, r), k , concat cutss)
   where
     (l, r) = snd $ maximum [(calc lr, lr) | lr <- findLRs 0 IM.empty $ map fromIntegral xs]
     cutss = [[1..l], [i+1|i<-[l+1..r-1],unsafeAt arr i<0], [r+2..n]]
     k = sum $ map length cutss

     arr      = listArray (0,n-1) xs                            :: UArray Int Int64
     sumArray = listArray (0,n-1) $ scanl1 (+) $ map (max 0) xs :: UArray Int Int64

     findLRs !i !im (x:xs) = case IM.lookup x im of
                              Nothing      -> findLRs (i+1) (IM.insert x [i] im) xs
                              Just (l:_)   -> findLRs (i+1) (IM.insert x [l,i] im) xs
     findLRs !_ !im _ = [(l, r) | [l,r] <- IM.elems im]

     calc (l, r)
       | l+1 > r-1 = unsafeAt arr l + unsafeAt arr r
       | otherwise = unsafeAt arr l + unsafeAt arr r + unsafeAt sumArray (r-1)  - unsafeAt sumArray l

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Int
import Data.Ix
import qualified Data.IntMap as IM
import Data.List
import Data.Ord

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

unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main = do
  n <- readLn
  xs <- map readInt.B.words <$> B.getLine
  let (res, len, cut) = solve n $ map fromIntegral xs
  putStrLn $ shows res " " ++ show len
  putStrLn.unwords $ map show cut

solve :: Int -> [Int64] -> (Int64, Int, [Int])
solve n xs = (calc (l, r), k , cut)
   where
     (l, r) = snd $ maximum [(calc lr, lr) | lr <- findLRs 0 IM.empty $ map fromIntegral xs]
     cut = [1..l]++[i+1|i<-[l+1..r-1],unsafeAt arr i<0]++[r+2..n]
     k = length cut

     arr      = listArray (0,n-1) xs                            :: UArray Int Int64
     sumArray = listArray (0,n-1) $ scanl1 (+) $ map (max 0) xs :: UArray Int Int64

     findLRs !i !im (x:xs) = case IM.lookup x im of
                              Nothing      -> findLRs (i+1) (IM.insert x [i] im) xs
                              Just (l:_)   -> findLRs (i+1) (IM.insert x [l,i] im) xs
     findLRs !_ !im _ = [(l, r) | [l,r] <- IM.elems im]

     calc (l, r)
       | l+1 > r-1 = unsafeAt arr l + unsafeAt arr r
       | otherwise = unsafeAt arr l + unsafeAt arr r + unsafeAt sumArray (r-1)  - unsafeAt sumArray l


{-# LANGUAGE ForeignFunctionInterface #-}

import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString as SB
import Data.ByteString.Internal (inlinePerformIO)
import Foreign.C.String (CString)
import Foreign.C (CDouble)
import Data.Maybe
import Data.List (maximumBy, minimum, foldl')
import Data.Array
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Debug.Trace

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO Double
unsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof
{-# INLINE unsafeReadDouble #-}
readDouble = unsafeReadDouble . SB.concat . LB.toChunks
readInt = fst . fromJust . LB.readInt

debug :: Show a => a -> b -> b
debug = trace . show
--debug _ = id

main = readFile "input.txt" >>= (writeFile "output.txt" . output . solve . parse . lines)

output (x,y) = show x ++ " " ++ show y

parse :: [String] -> (Int, Int, [(Int, Int)])
parse [nm, sk, pts] =
  let [n, m] = map read . words $ nm
      k = read sk :: Int
      lst = map read . words $ pts
      trees = [ (lst !! i, lst !! (i+1)) | i <- [0, 2 .. length lst - 1]]
  in (n, m, trees)

solve (n, m, start) =
  let allTrees = [(x, y, d x y) | x <- [1..n], y <- [1..m] ]
      (x, y, _) = maximumBy (\ (_, _, d) (_, _, e) -> compare d e) allTrees
      d x y = minimum [abs(i-x) + abs(j-y) | (i, j) <- start ]
  in (x,y)

import Ix

calc :: (Int, Int) -> (Int, Int) -> Int
calc x y = (abs fstdiff) + (abs snddiff)
    where fstdiff = (fst x) - (fst y)
          snddiff = (snd x) - (snd y)

burnMinute :: [(Int, Int)] -> (Int, Int) -> Int
burnMinute points target = minimum $ map ( `calc` target) points

calcMaxMinute :: [(Int, Int)] -> [(Int, Int)] -> Int
calcMaxMinute points area = maximum $ map (burnMinute points) area

calcAns :: [(Int, Int)] -> [(Int, Int)] -> Int-> (Int, Int) -> (Int, Int)
calcAns points (x : xs) s t | burnMinute points x >= s = calcAns points xs (burnMinute points x) x
                            | otherwise = calcAns points xs s t

calcAns _ [] _ t = t

makepoints :: String -> [(Int, Int)]
makepoints str = f $ words str
    where f [] = []
          f (x : y : xs) = ((read x) :: Int, (read y) :: Int) : f xs

printAns :: (Int, Int) -> String
printAns (a, b) = show a ++ " " ++ show b

main :: IO ()
main = do
       str <- readFile "input.txt"
       let x = (read $ head $ words $ head $ lines str) :: Int
       let y = (read $ head $ tail $ words $ head $ lines str) :: Int
       let points = makepoints $ head $ tail $ tail $ lines str
       let ans = calcAns points ((range ((1, 1), (x, y))) :: [(Int, Int)]) 0 (1, 1)
       writeFile "output.txt" $ printAns ans


import Data.List

solve :: [Int] -> Int
solve (n:xs)
  | head as == head bs = n - a - b + max a b - 1
  | otherwise = n - 1
  where
    as = head $ group xs
    bs = head $ reverse $ group xs
    a = length as
    b = length bs

tests :: [[Int]]
tests = [ [5, 1, 2, 3, 2, 3]
        , [3, 1, 2, 1]
        , [7, 1, 1, 3, 1, 1, 1, 1]
        ]

main = interact $ show . solve . map read . words

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

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

solve :: [Int] -> Int
solve xs
    | f /= l    = n - 1
    | otherwise = n - 1 - (min a b)
    where n = length xs
          f = head xs
          l = last xs
          a = length $ head $ group xs
          b = length $ last $ group xs

main :: IO ()
main = do
    _ <- readInt
    v <- readInts
    print $ solve v

import Control.Monad
import Data.List
import Data.Maybe
import Data.Char

import qualified Data.ByteString.Char8 as B
readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

solve :: [Int] -> Int
solve xs
    | a /= b    = (length xs) - 1
    | otherwise = (max (length (dropWhile (==b) xs)) (length (dropWhile (==a) ys))) - 1
        where a = head xs
              b = last xs
              ys = reverse xs

main :: IO ()
main = do
    _ <- readInt
    v <- readInts
    print $ solve v

--prewritten code: https://github.com/antma/algo
{-# 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

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

f (x:xs) = length $ dropWhile (== x) $ reverse xs

solve :: [Int] -> Builder
solve (n:a) = intDec res <> char7 '\n'
  where
    b = take n a
    !res = max (f b) (f $ reverse b)

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

import Data.List

solve :: [Int] -> Int
solve xs
  | head as /= head bs = n - 1
  | otherwise = n - min (length as) (length bs)
  where
    as = head $ group xs
    bs = head $ reverse $ group xs
    n = length xs

tests :: [[Int]]
tests = [ [1, 2, 3, 2, 3]
        , [1, 2, 1]
        , [1, 1, 3, 1, 1, 1]
        ]

main = interact $ show . solve . map read . tail . words