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


import           Control.Monad
import           Control.Monad.ST
import           Data.Array
import           Data.Array.ST.Safe
import           Data.List
import           Data.Ord
import           Data.STRef
import           Numeric

(|>) = flip (.)

int :: (Eq a, Num a) => String -> a
int x = fst $ readDec x !! 0

ints :: (Eq a, Num a) => String -> [a]
ints = map int . words

main = interact $
  lines
  |> solverLoop
  |> unlines

data Node = Node {
  parent  :: Int,
  inMST   :: Bool,
  nodeNum :: Int,
  cost    :: Integer
} deriving (Show)

solverLoop :: [String] -> [String]
solverLoop (ts:xs) = [
    showInt totalCost "",
    showInt (length buildPlants) "",
    unwords $ map ((\i -> showInt i "") . nodeNum) buildPlants,
    showInt (length buildWires) ""
  ] ++ map (\(Node p _ v _) -> showInt p (" " ++ showInt v "")) buildWires
    where
      t = int ts
      coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]
      (cs:ks:_) = drop t xs
      wires = array (1, t) $ zip [1..t] (ints ks)
      costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)
      nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf
      totalCost = sum $ map cost nodes
      (buildPlants, buildWires) = partition ((== 0) . parent) nodes

mst t initial costf = runST $ do
  nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)
  replicateM_ t $ do
    elems <- getElems nodes
    let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems
    writeArray nodes v node {inMST = True}
    forM_ [1..t] $ \vn -> do
      let w = costf v vn
      node@(Node p inMst vn w2) <- readArray nodes vn
      when (not inMst && w < w2) $
        writeArray nodes vn node {parent = v, cost = w}
  getElems nodes

dist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)

import           Control.Monad
import           Control.Monad.ST
import           Data.Array
import           Data.Array.ST.Safe
import           Data.List
import           Data.Ord
import           Data.STRef
import           Numeric

(|>) = flip (.)

int :: (Eq a, Num a) => String -> a
int x = fst $ readDec x !! 0

ints :: (Eq a, Num a) => String -> [a]
ints = map int . words

main = interact $
  lines
  |> solverLoop
  |> unlines

data Node = Node {
  parent  :: Int,
  inMST   :: Bool,
  nodeNum :: Int,
  cost    :: Integer
} deriving (Show)

solverLoop :: [String] -> [String]
solverLoop (ts:xs) = map (unwords) $ [
    [show totalCost],
    [show $ length buildPlants],
    map (show . nodeNum) buildPlants,
    [show $ length buildWires]
  ] ++ map (\(Node p _ v _) -> [show p, show v]) buildWires
    where
      t = int ts
      coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]
      (cs:ks:_) = drop t xs
      wires = array (1, t) $ zip [1..t] (ints ks)
      costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)
      nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf
      totalCost = sum $ map cost nodes
      (buildPlants, buildWires) = partition ((== 0) . parent) nodes

mst t initial costf = runST $ do
  nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)
  replicateM_ t $ do
    elems <- getElems nodes
    let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems
    writeArray nodes v node {inMST = True}
    forM_ [1..t] $ \vn -> do
      let w = costf v vn
      node@(Node p inMst vn w2) <- readArray nodes vn
      when (not inMst && w < w2) $
        writeArray nodes vn node {parent = v, cost = w}
  getElems nodes

dist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)

import           Control.Monad
import           Control.Monad.ST
import           Data.Array
import           Data.Array.ST.Safe
import           Data.List
import           Data.Ord
import           Data.STRef
import           Numeric

(|>) = flip (.)

int :: (Eq a, Num a) => String -> a
int x = fst $ readDec x !! 0

ints :: (Eq a, Num a) => String -> [a]
ints = map int . words

main = interact $
  lines
  |> solverLoop
  |> unlines

data Node = Node {
  parent  :: Int,
  inMST   :: Bool,
  nodeNum :: Int,
  cost    :: Integer
} deriving (Show)

solverLoop :: [String] -> [String]
solverLoop (ts:xs) = map (unwords) $ [
    [show totalCost],
    [show $ length buildPlants],
    map (show . nodeNum) buildPlants,
    [show $ length buildWires]
  ] ++ map (\(Node p _ v _) -> [show p, show v]) buildWires
    where
      t = int ts
      coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]
      (cs:ks:_) = drop t xs
      wires = array (1, t) $ zip [1..t] (ints ks)
      costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)
      nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf
      totalCost = sum $ map cost nodes
      (buildPlants, buildWires) = partition ((== 0) . parent) nodes

mst t initial costf = runST $ do
  nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)
  forM_ [1..t] $ \_ -> do
    elems <- getElems nodes
    let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems
    writeArray nodes v node {inMST = True}
    forM_ [1..t] $ \vn -> do
      let w = costf v vn
      node@(Node p inMst vn w2) <- readArray nodes vn
      when (not inMst && w < w2) $
        writeArray nodes vn node {parent = v, cost = w}
  getElems nodes

dist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)

import Control.Monad
import           Control.Monad.ST
import           Data.Array
import Data.Array.ST.Safe
import           Data.List
import           Numeric
import Data.Tuple
import Data.STRef

(|>) = flip (.)

int :: (Eq a, Num a) => String -> a
int x = fst $ readDec x !! 0

ints :: (Eq a, Num a) => String -> [a]
ints = map int . words

count x = length . filter (== x)

main = interact $
  lines
  |> solverLoop
  |> unlines

solverLoop :: [String] -> [String]
solverLoop (ts:xs) = map (unwords) $ [
    [show totalCost],
    [show $ length buildPlants],
    map show buildPlants,
    [show $ length buildWires]
  ] ++ map (map show) buildWires
    where
      t = int ts
      coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]
      (cs:ks:_) = drop t xs
      wires = array (1, t) $ zip [1..t] (ints ks)
      (totalCost, buildPlants, buildWires) = runST $ do
        plantsRef <- newSTRef []
        wiresRef <- newSTRef []
        totalCost <- newSTRef 0
        nodes <- newListArray (1, t) (map (\i -> (i, 0, False)) $ ints cs) :: ST s (STArray s Int (Integer, Int, Bool))
        forM_ [1..t] $ \_ -> do
          ascs <- getAssocs nodes
          let ((w,u,_), v) = minimum $ map swap $ filter (\(_,(_,_,c)) -> not c) ascs
          if u == 0
            then modifySTRef plantsRef (\ps -> v:ps)
            else modifySTRef wiresRef (\ws -> [u,v]:ws)
          modifySTRef totalCost (+ w)
          writeArray nodes v (w,u,True)
          forM_ [1..t] $ \vn -> do
            let cost = (wires ! v + wires ! vn) * dist (coords ! v) (coords ! vn)
            (cost2,_,inMst) <- readArray nodes vn
            if not inMst && cost < cost2
              then writeArray nodes vn (cost,v,inMst)
              else return ()
        (,,) <$> readSTRef totalCost <*> readSTRef plantsRef <*> readSTRef wiresRef

dist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)

import           Control.Monad
import           Control.Monad.ST
import           Data.Array
import           Data.Array.ST.Safe
import           Data.List
import           Data.Ord
import           Data.STRef
import           Numeric

(|>) = flip (.)

int :: (Eq a, Num a) => String -> a
int x = fst $ readDec x !! 0

ints :: (Eq a, Num a) => String -> [a]
ints = map int . words

main = interact $
  lines
  |> solverLoop
  |> unlines

data Node = Node {
  parent  :: Int,
  inMST   :: Bool,
  nodeNum :: Int,
  cost    :: Integer
} deriving (Show)

solverLoop :: [String] -> [String]
solverLoop (ts:xs) = map (unwords) $ [
    [show totalCost],
    [show $ length buildPlants],
    map (show . nodeNum) buildPlants,
    [show $ length buildWires]
  ] ++ map (\(Node p _ v _) -> [show p, show v]) buildWires
    where
      t = int ts
      coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]
      (cs:ks:_) = drop t xs
      wires = array (1, t) $ zip [1..t] (ints ks)
      costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)
      nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf
      totalCost = sum $ map cost nodes
      (buildPlants, buildWires) = partition ((== 0) . parent) nodes

mst t initial costf = runST $ do
  nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)
  forM_ [1..t] $ \_ -> do
    elems <- getElems nodes
    let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems
    writeArray nodes v node {inMST = True}
    let updateKey node@(Node p inMst vn w2) = if (not inMst && costf v vn < w2)
        then Just node { parent = v, cost = costf v vn }
        else Nothing
    mapArrayInPlace updateKey nodes
  getElems nodes

mapArrayInPlace :: (MArray a e m, Ix i) => (e -> Maybe e) -> a i e -> m ()
mapArrayInPlace f array = do
  assocs <- getAssocs array
  forM_ assocs $ \(i, e) ->
    case f e of
      Just x  -> writeArray array i x
      Nothing -> return ()

dist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)

import Control.Monad
import           Control.Monad.ST
import           Data.Array
import Data.Array.ST.Safe
import           Data.List
import           Numeric
import Data.Tuple

(|>) = flip (.)

int :: (Eq a, Num a) => String -> a
int x = fst $ readDec x !! 0

ints :: (Eq a, Num a) => String -> [a]
ints = map int . words

count x = length . filter (== x)

main = interact $
  lines
  |> solverLoop
  |> unlines

solverLoop :: [String] -> [String]
solverLoop (ts:xs) = map (unwords) $ [
    [show totalCost],
    [show $ length buildPlants],
    map show buildPlants,
    [show $ length buildWires]
  ] ++ map (map show) buildWires
    where
      t = int ts
      coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]
      (cs:ks:_) = drop t xs
      wires = array (1, t) $ zip [1..t] (ints ks)
      edges = runST $ do
        nodes <- newListArray (1, t) (map (\i -> (i, 0, False)) $ ints cs) :: ST s (STArray s Int (Integer, Int, Bool))
        forM_ [1..t] $ \_ -> do
          a <- getAssocs nodes
          let ((w,u,_), v) = minimum $ map swap $ filter (\(_,(_,_,c)) -> not c) a
          writeArray nodes v (w,u,True)
          forM_ [1..t] $ \vn -> do
            let cost = (wires ! v + wires ! vn) * dist (coords ! v) (coords ! vn)
            (cost2,_,inMst) <- readArray nodes vn
            if not inMst && cost < cost2
              then writeArray nodes vn (cost,v,inMst)
              else return ()
        getElems nodes
      totalCost = sum $ map (\(a,_,_) -> a) edges
      (buildPlants, buildWires) = detail $ zip [1..t] edges

detail :: [(Int, (Integer, Int, Bool))] -> ([Int], [[Int]])
detail [] = ([],[])
detail ((u, (w, v, _)):xs)
  | v == 0 = (u:ps', ws')
  | otherwise = (ps', [u,v]:ws')
  where
    (ps', ws') = detail xs

dist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)

import           Control.Monad
import           Control.Monad.ST
import           Data.Array
import           Data.Array.ST.Safe
import           Data.List
import           Data.Ord
import           Data.STRef
import           Numeric

(|>) = flip (.)

int :: (Eq a, Num a) => String -> a
int x = fst $ readDec x !! 0

ints :: (Eq a, Num a) => String -> [a]
ints = map int . words

main = interact $
  lines
  |> solverLoop
  |> unlines

data Node = Node {
  parent  :: Int,
  inMST   :: Bool,
  nodeNum :: Int,
  cost    :: Integer
} deriving (Show)

solverLoop :: [String] -> [String]
solverLoop (ts:xs) = [
    showInt totalCost "",
    showInt (length buildWires) "",
    unwords $ map ((\i -> showInt i "") . nodeNum) buildPlants,
    showInt (length buildWires) ""
  ] ++ map (\(Node p _ v _) -> showInt p (" " ++ showInt v "")) buildWires
    where
      t = int ts
      coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]
      (cs:ks:_) = drop t xs
      wires = array (1, t) $ zip [1..t] (ints ks)
      costf v w = (wires ! v + wires ! w) * dist (coords ! v) (coords ! w)
      nodes = mst t (map (uncurry $ Node 0 False) $ zip [1..t] (ints cs)) costf
      totalCost = sum $ map cost nodes
      (buildPlants, buildWires) = partition ((== 0) . parent) nodes

mst t initial costf = runST $ do
  nodes <- newListArray (1, t) initial :: ST s (STArray s Int Node)
  replicateM_ t $ do
    elems <- getElems nodes
    let node@(Node u _ v w) = minimumBy (comparing cost) $ filter (not . inMST) elems
    writeArray nodes v node {inMST = True}
    forM_ [1..t] $ \vn -> do
      let w = costf v vn
      node@(Node p inMst vn w2) <- readArray nodes vn
      when (not inMst && w < w2) $
        writeArray nodes vn node {parent = v, cost = w}
  getElems nodes

dist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)

import Control.Monad
import           Control.Monad.ST
import           Data.Array
import Data.Array.ST.Safe
import           Data.List
import           Numeric
import Data.Tuple

(|>) = flip (.)

int :: (Eq a, Num a) => String -> a
int x = fst $ readDec x !! 0

ints :: (Eq a, Num a) => String -> [a]
ints = map int . words

count x = length . filter (== x)

main = interact $
  lines
  |> solverLoop
  |> unlines

solverLoop :: [String] -> [String]
solverLoop (ts:xs) = map (unwords . map show) $ [
    [totalCost],
    [length buildPlants],
    buildPlants,
    [length buildWires]
  ] ++ buildWires
    where
      t = int ts
      coords = array (1, t) [(i, (x, y)) | (i, (x:y:_)) <- zip [1..t] (map ints xs) ]
      (cs:ks:_) = drop t xs
      wires = array (1, t) $ zip [1..t] (ints ks)
      edges = runST $ do
        nodes <- newListArray (1, t) (map (\i -> (i, 0, False)) $ ints cs) :: ST s (STArray s Int (Int, Int, Bool))
        forM_ [1..t] $ \_ -> do
          a <- getAssocs nodes
          let ((w,u,_), v) = minimum $ map swap $ filter (\(_,(_,_,c)) -> not c) a
          writeArray nodes v (w,u,True)
          forM_ [1..t] $ \vn -> do
            let cost = (wires ! v + wires ! vn) * dist (coords ! v) (coords ! vn)
            (cost2,_,inMst) <- readArray nodes vn
            if not inMst && cost < cost2
              then writeArray nodes vn (cost,v,inMst)
              else return ()
        getElems nodes
      totalCost = sum $ map (\(a,_,_) -> a) edges
      (buildPlants, buildWires) = detail $ zip [1..t] edges

detail [] = ([],[])
detail ((u, (w, v, _)):xs)
  | v == 0 = (u:ps', ws')
  | otherwise = (ps', [u,v]:ws')
  where
    (ps', ws') = detail xs

dist (x1,y1) (x2,y2) = abs (x1 - x2) + abs (y1 - y2)


import Control.Monad

getA = fmap (map read . words) getLine
hypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2

main = do
	[n] <- getA
	[k, e] <- getA
	[x, y] <- getA
	p <- replicateM n getA
	putStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\[i, j] -> hypot (i - x) (j - y)) p

gao n k e d = gao' 0 3000 where
	gao' l r = if r - l < 0.1 ^ 8 then m else if q > e then gao' l m else gao' m r where
		m = (l + r) / 2
		p = map (\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d
		q = sum $ drop k $ go p

go [] = [1]
go (p:ps) = let q = go ps in zipWith (\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])

import Control.Monad

getA = fmap (map read . words) getLine
hypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2

main = do
	[n] <- getA
	[k, e] <- getA
	[x, y] <- getA
	p <- replicateM n getA
	putStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\[i, j] -> hypot (i - x) (j - y)) p

gao n k e d = gao' 0 2000 where
	gao' l r = if r-l<0.1^8 then m else if q > e then gao' l m else gao' m r where
		m = (l + r) / 2
		p = map (\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d
		q = sum $ drop k $ go p

go [] = [1]
go (p:ps) = let q = go ps in zipWith (\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])

import Control.Monad

getA = fmap (map read . words) getLine
hypot x y = sqrt . fromIntegral $ x ^ 2 + y ^ 2

main = do
	[n] <- getA
	[k, e] <- getA
	[x, y] <- getA
	p <- replicateM n getA
	putStr $ show $ gao n k (1 - fromIntegral e/1000) $ map (\[i, j] -> hypot (i - x) (j - y)) p

gao n k e d = gao' 0 2000 where
	gao' l r = if abs(l-r)<0.0000001 then m else if q > e then gao' l m else gao' m r where
		m = (l + r) / 2
		p = map (\i -> if i <= m then 1 else exp $ 1 - (i / m) ^ 2) d
		q = sum $ drop k $ go p

go [] = [1]
go (p:ps) = let q = go ps in zipWith (\i j -> p * i + (1 - p) * j) (0:q) (q ++ [0])


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

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

main = do
  _ <- readInt1 <$> BS.getLine
  as <- readIntN <$> BS.getLine
  _ <- readInt1 <$> BS.getLine
  bs <- readIntN <$> BS.getLine
  cs <- readIntN <$> BS.getLine
  print $ solve as $ zip bs cs

solve as bcs = fst . maximumBy (compare `on` snd) . zip [1..] $ map score bcs where
  score :: (Int,Int) -> Int64
  score (b,c) = (fromIntegral $ cnt b) * 200000 + (fromIntegral $ cnt c)
  cnt x = M.findWithDefault 0 x m
  m = loop as M.empty where
    loop [] m' = m'
    loop (a:as) m' = loop as (M.insertWith (+) a 1 m')

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

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

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

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

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

readInt641 :: BS.ByteString -> Int64
readInt641 = fromIntegral . fst . fromJust . BS.readInteger

readInt642 :: BS.ByteString -> (Int64,Int64)
readInt642 = toTuple . readInt64N

readInt643 :: BS.ByteString -> (Int64,Int64,Int64)
readInt643 = toTriple . readInt64N

readInt64N :: BS.ByteString -> [Int64]
readInt64N =  map readInt641 . BS.words

readInteger1 :: BS.ByteString -> Integer
readInteger1 = fst . fromJust . BS.readInteger

readInteger2 :: BS.ByteString -> (Integer,Integer)
readInteger2 = toTuple . readIntegerN

readInteger3 :: BS.ByteString -> (Integer,Integer,Integer)
readInteger3 = toTriple . readIntegerN

readIntegerN :: BS.ByteString -> [Integer]
readIntegerN =  map readInteger1 . BS.words

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

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

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

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

-- if not applying, use "const"

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

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

import Data.Maybe
import Control.Applicative
import qualified Data.List as L
import           Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as Map
import qualified Data.ByteString.Char8 as BS

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

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

build_map :: [Int] -> (IntMap Int) -> (IntMap Int)
build_map [] mp = mp
build_map (x:xs) mp = build_map xs $ Map.insertWith (+) x 1 mp

f :: (IntMap Int) -> (Int, Int) -> (Int, Int)
f mp (a,b) = (Map.findWithDefault 0 a mp, Map.findWithDefault 0 b mp)

main :: IO ()
main = do
  n <- readLn :: IO Int
  -- la <- getLine
  -- let a = map read (words la) :: [Int]
  a <- readIntN <$> BS.getLine
  m <- readLn :: IO Int
  -- lb <- getLine
  -- lc <- getLine
  -- let b = map read (words lb) :: [Int]
  -- let c = map read (words lc) :: [Int]
  b <- readIntN <$> BS.getLine
  c <- readIntN <$> BS.getLine
  let bc = zip b c
  let ma = build_map a Map.empty
  print . snd $ L.maximumBy compare $ zip (map  (f ma) bc) [1..]

import qualified Data.Map as M
import Control.Applicative
import Control.Monad

import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Text.Read (decimal)
import System.IO (stdin)

tread s = case decimal s of
  Right (v,_) -> v
  Left e -> error e

count xs = foldr (\a m -> M.insertWith (\new old -> old + 1) a 1 m) M.empty xs

m ! v = case M.lookup v m of
  Just v -> v
  Nothing -> 0

aux [] [] i ans res freq = ans
aux (x:xs) (y:ys) i ans res@(a,b) freq
  | res < (freq ! x, freq ! y) = aux xs ys (i+1) i (freq ! x, freq ! y) freq
  | otherwise = aux xs ys (i+1) ans res freq

main = do
  n <- readLn :: IO Int
  as <- map tread . T.words <$> (TIO.hGetLine stdin) :: IO [Int]
  m <- readLn :: IO Int
  bs <- map tread . T.words <$> (TIO.hGetLine stdin) :: IO [Int]
  cs <- map tread . T.words <$> (TIO.hGetLine stdin) :: IO [Int]
  let freq = count as
  let ans = aux bs cs 0 0 (0,0) freq
  print $ ans + 1

import Data.List
import Control.Arrow
import Control.Applicative
import Control.Monad
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Text.Read (decimal)
import System.IO (stdin)
import qualified Data.Map as Map

tread s = case decimal s of
    Right (v, _) -> v
    Left e -> error e

main :: IO()
main = do
    _ <- getLine
    a <- map tread . T.words <$> TIO.hGetLine stdin :: IO [Int]
    _ <- getLine
    b <- map tread . T.words <$> TIO.hGetLine stdin :: IO [Int]
    c <- map tread . T.words <$> TIO.hGetLine stdin :: IO [Int]
    let f = Map.fromList $ frequency a
    print $ solve b c 1 0 0 1 f

frequency :: Ord a => [a] -> [(a, Int)]
frequency = map (head &&& length) . group . sort

removeMaybe :: Maybe Int -> Int
removeMaybe (Just a) = a
removeMaybe Nothing = 0

solve :: [Int] -> [Int] -> Int -> Int -> Int -> Int -> Map.Map Int Int -> Int
solve [] [] _ _ _ maxIdx _ = maxIdx
solve (b:bs) (c:cs) idx maxVal1 maxVal2 maxIdx fre =
    let newVal1 = removeMaybe $ Map.lookup b fre
        newVal2 = removeMaybe $ Map.lookup c fre
    in if newVal1 > maxVal1 || (newVal1 == maxVal1 && newVal2 > maxVal2)
       then solve bs cs (idx + 1) newVal1 newVal2 idx fre
       else solve bs cs (idx + 1) maxVal1 maxVal2 maxIdx fre

import Data.Map.Strict (empty, insertWith, findWithDefault)
import Data.Ord (comparing)
import Data.List (maximumBy)

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C
import           Data.Maybe (fromJust)

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

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

--
-- MAIN
--

main :: IO ()
main = do
  n      <- readInt
  lang   <- readInts
  m      <- readInt
  sounds <- readInts
  subs   <- readInts
  let langmap = foldl (\mp k -> insertWith (+) k 1 mp) empty lang
      happy   = getHappy <$> zip sounds subs
      getHappy (snd, sbt) = (findWithDefault 0 snd langmap, findWithDefault 0 sbt langmap)
      (_, ans) = maximumBy (comparing fst) $ zip happy [1..]
  print ans

import Control.Monad
import Control.Applicative

import qualified Data.Map as M
import Data.Ord (comparing)
import Data.List (maximumBy)

maxAux [] [] i freq aMax subV subI = subI
maxAux (x:xs) (y:ys) i freq aMax subV subI
  | freq !!! x == aMax = if freq !!! y > subV
                         then maxAux xs ys (i+1) freq aMax (freq !!! y) i
                         else maxAux xs ys (y+1) freq aMax subV subI
  | otherwise = maxAux xs ys (i+1) freq aMax subV subI

(!!!) ::   M.Map Int Int -> Int -> Int
m !!! v = case M.lookup v m of
    Just v -> v
    Nothing -> 0

main = do
  n <- readLn :: IO Int
  ls <- map read . words <$> getLine :: IO [Int]
  m <- readLn :: IO Int
  aud <- map read . words <$> getLine :: IO [Int]
  sub <- map read . words <$> getLine :: IO [Int]

  let freq = foldr (\a m -> M.insertWith (\new old -> old + 1) a 1 m) M.empty ls

  let subMax = maximumBy (comparing (freq !!!)) sub
  let audMax = maximumBy (comparing (freq !!!)) aud

  let ans = maxAux aud sub 0 freq audMax 0 0

  print (ans+1)


{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List
import Data.Function

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (_ : l : rest) = (itoline . solve . linetois) l : tcio rest
  linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: [Int] -> Int
solve xs = if null u then (-1) else (snd.head.head) u  where u = dropWhile (not.null.drop 1) $ groupBy ((==) `on` fst) $ sort $ zip xs [1..]

{-# LANGUAGE GADTs, TemplateHaskell, DeriveFunctor, OverloadedStrings #-}

import Data.List
import qualified Data.ByteString.Char8 as B8
import Data.Maybe
import Data.Int
import Text.Printf
import Data.Function ( (&), on )
import Data.Functor
import Control.Arrow ((>>>))
import Control.Monad (forM_)
import Data.Char (isAlpha)

readIntB8 :: B8.ByteString -> Maybe Int
readIntB8 = B8.readInt >>> fmap fst

solve :: [Int] -> Maybe Int
solve as = do
    let uniqueAs = sort as & group & filter (\x -> length x == 1) & concat
    result <- listToMaybe uniqueAs
    index <- elemIndex result as
    return $ index + 1

mainCase :: IO ()
mainCase = do
    Just n <- B8.getLine <&> readIntB8
    as <- B8.getLine <&> B8.words <&> map (readIntB8 >>> fromJust)
    let answer = fromMaybe (-1) $ solve as
    printf "%d\n" answer

main :: IO ()
main = do
    Just t <- B8.getLine <&> readIntB8
    forM_ [1 .. t] $ const mainCase

{-
n participants
i-th participant chose number ai
participant that chooses the smallest unique number wins

find index of the participant who won, or -1 if no winner
index is 1-based (1 to n)
answer t independent test cases

input:
t, number of test cases
first line number participants
second line n integers
-}

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

main = do
  cases <- read <$> getLine
  replicateM cases $ do
    _ <- getLine
    participantNumbers <- ((fmap . fmap) read) $ words <$> getLine
    putStrLn $ show $ minUniqueIndex participantNumbers

minUniqueIndex :: [Int] -> Int
minUniqueIndex xs =
  if null uniques
     then -1
     else 1 + (fromJust $ findIndex (== head uniques) xs)
  where
    uniques = Map.keys $ Map.filter (<2) $ Map.fromListWith (+) $ map (flip (,) 1) xs

import Control.Arrow ((>>>))
import Data.List (groupBy, sort)

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

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

solve :: [Int] -> Int
solve xs
  | null ys = -1
  | otherwise = snd . head . head $ ys
  where
    ys = filter ((== 1) . length) . groupBy (eq fst) . sort $ zip xs [1 ..]
    eq p x y = p x == p y

import Data.List
main :: IO ()
main = interact $ unlines . map show . solve . map read . tail . words

solve :: [Int] -> [Int]
solve [] = []
solve (n:rs) = findMin cn :(solve rest)
    where (an,rest) = splitAt n rs
          bn = zip [1..n] an
          cn = sortBy (\(_,vi) (_,vj) -> compare vi vj) bn

findMin :: [(Int,Int)] -> Int
findMin [] = -1
findMin [(i,vi)] = i
findMin ((i,vi):(j,vj):rs)
    | (vi /= vj) = i
    | otherwise = findMin $ dropWhile (\(a,va) -> va == vi) rs

import Data.List

solve :: [Int] -> Int
solve a
  | null b = -1
  | otherwise = snd . head . head $ b
  where
    b = filter ((==1) . length). groupBy (\x y -> fst x == fst y) . sort $ zip a [1..]

f [] = []
f (_:x:xs) = solve x : f xs

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

import Data.List

solve [] = -1
solve (x:xs) = if (length $ takeWhile (==x) xs) >= 1
  then solve $ dropWhile (==x) xs
  else x

f [] = []
f (_:x:xs) = solve (sort x) : f xs

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


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

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

readInt :: B.ByteString -> Int
readInt = fromJust . fmap fst . B.readInt
readInts :: IO [Int]
readInts = map readInt . B.words <$> B.getLine

ifTE :: Bool -> a -> a -> a
ifTE x y z = if x then y else z

boolean :: a -> a -> Bool -> a
boolean x y z = ifTE z x y

main :: IO ()
main = do
    [n,m,k] <- readInts
    l <- ifTE (m <= n) id transpose <$> replicateM n readInts
    let w = min n m
        cost = curry $ sum . uncurry (zipWith ((boolean 0 1.) . (==)))
        f = sum . flip map l . (uncurry min.) . ((id &&& (w-)).) . cost
        res = minimum $ map f $ ifTE (w <= k) (replicateM w [0,1]) l
    print $ if res <= k then res else -1

import Control.Arrow
import Data.Bits
import Data.List

solve ([n, m, k] : a)
	| n < m     = solve ([m, n, k] : transpose a)
	| ans <= k  = ans
	| otherwise = -1
	where
		xs = map (foldl (\x b -> 2 * x + b) 0) a
		work y = sum $ map (uncurry min . (id &&& (m-)) . toInteger . popCount . xor y) xs
		ans = minimum . map work $ if m > k then xs else [0 .. 2^m-1]

main = interact $ show . solve . map (map read . words) . lines

import Control.Arrow
import Data.Bits
import Data.List

solve ([n, m, k] : a) = if n < m then solve ([m, n, k] : transpose a) else
	let
		xs = map (foldl (\x b -> 2 * x + b) 0) a
		ys = if m > k then xs else [0 .. 2 ^ m - 1]
		work y = sum $ map (uncurry min . (id &&& (m-)) . toInteger . popCount . (y `xor`)) xs
		cost = minimum $ map work ys
	in if cost <= k then cost else -1

main = interact $ show . solve . map (map read . words) . lines

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
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 = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = 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)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i
    where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
inf = maxBound `div` 2 :: Int

main = do
    [n,m,k] <- readInts
    l <- replicateM n readInts
    let l1 = if m <= n then l else transpose l
    let w = min n m
    let res = minimum $ do
        xs <- if w <= k then replicateM w [0,1] else l1
        return $ sum [ min (cost xs r) (cost (neg xs) r) | r <- l1 ]
    print $ if res <= k then res else -1

neg :: [Int] -> [Int]
neg = map (1-)

cost :: [Int] -> [Int] -> Int
cost xs ys = sum $ zipWith (\a b -> if a == b then 0 else 1) xs ys
{-
 - w <= hとする
 - w <= k ならば
 -  xs <- [0,1]^w
 - w > k ならば
 -  xs <- rows
 - とするこのときの最小コストは
 - sum [ min (popcount $ xs `xor` ri) (popcount $ not xs `xor` ri) | ri <- rs]
 -
 - -}