import Control.Monad

solve n y | y<=3 = 0
          | y>=n-1 = 0
          | otherwise = minimum [abs $ n-2-y,abs $ 2*y - n - 2, abs $ y-4]

main :: IO ()
main = do
    ts <- getLine

    replicateM (read ts) $ do
        input <- getLine
        let n = read  $ input ::Int
        putStrLn.show. maximum $ [solve n (2*div n 3), solve n (2*div n 3+1),solve n (2*div n 3+2)]

    return ()

import Data.Char

bruteForce m = (div m 3) - 1

main = do
  rawInput <- getContents
  let input = tail $ lines rawInput
  let ns = map read input :: [Int]
  let ms = map (\n -> n-3) ns
  let output = map bruteForce ms
  putStr (unlines $ map show output)

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

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

{-# options_ghc -O3                              #-}

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

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

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

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

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

solve n = min (b-a) (c-b)
  where
    s = n-3
    a = 1 :: Int
    b = (s+1) `div` 3
    c = s - (a+b)

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = read <$> getLine >>= print . minP
minP n = let x = (div n 3) - 2 in
           max (min (x-1) (n - 4 - 2*x)) (min x (n - 4 - 2*(x+1)))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

{- END OF GENERAL -}

solve :: Int -> Int
solve n = maximum values
    where
        mid = n `div` 3
        values = do
            l1 <- [1 .. 10]
            l2 <- [mid - 10 .. mid + 10]
            let l3 = n - l1 - l2 - 3
            guard $ l1 > 0
            guard $ l2 > 0
            guard $ l3 > 0
            return $ minimum [abs (l1 - l2), abs (l2 - l3), abs (l3 - l1)]

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


import Control.Monad

getDiv :: Integer -> String
getDiv x = if (x <= 1399) then "Division 4" else if (x <= 1599) then "Division 3" else if (x <= 1899) then "Division 2" else "Division 1"

main :: IO ()
main = do
    t <- getLine
    nrs <- replicateM (read t) getLine
    mapM_ putStrLn $ map getDiv $ map (read :: String -> Integer) nrs

division :: Int -> String
division x | x >= 1900 = "Division 1" | x >= 1600 = "Division 2" | x >= 1400 = "Division 3" | otherwise = "Division 4"

solve :: [Int] -> [String]
solve xs = map division $ xs

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

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

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

readIntArr :: IO [Int]
readIntArr = do
  arr <- words <$> getLine
  pure $ map parseInt arr

calc :: Int -> String
calc x
  | x < 1400 = "Division 4"
  | x < 1600 = "Division 3"
  | x < 1900 = "Division 2"
  | otherwise = "Division 1"

solve :: IO ()
solve = do
  rating <- readInt
  putStrLn $ calc rating

for :: Int -> IO () -> IO ()
for 0 _ = pure ()
for i f = do
  f
  for (i - 1) f

main :: IO ()
main = do
  n <- readInt
  for n solve

main :: IO ()
main = interact $ unlines . map(f.(read::String->Int)).tail .words
f a
  |a <1400 = "Division 4"
  |a <1600 = "Division 3"
  |a <1900 = "Division 2"
  |otherwise = "Division 1"

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

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

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

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

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

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

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

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace

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

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

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

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

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

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

{- END OF GENERAL -}

solve :: Int -> Int
solve rating
    | 1_900 <= rating = 1
    | 1_600 <= rating && rating <= 1_899 = 2
    | 1_400 <= rating && rating <= 1_599 = 3
    | rating <= 1_399 = 4

main :: IO ()
main = do
    n <- B8.getLine <&> readIntB8
    replicateM_ n $ do
        rating <- B8.getLine <&> readIntB8
        let answer = solve rating
        printf "Division %d\n" answer

division :: Int -> String
division x | x >= 1900 = "Division 1" | x >= 1600 = "Division 2" | x >= 1400 = "Division 3" | otherwise = "Division 4"

main :: IO()
main = interact $ unlines . map show . map division . tail . map read . words

division :: Int -> String
division x | x >= 1900 = "Division 1" | x >= 1600 = "Division 2" | x >= 1400 = "Division 3" | otherwise = "Division 4"

main :: IO()
main = interact $ show . unwords . map division . tail . map read . words

division :: Int -> String
division x | x >= 1900 = "Division 1 " | x >= 1600 = "Division 2 " | x >= 1400 = "Division 3 " | otherwise = "Division 4 "

main :: IO()
main = interact $ show . unlines . map division . tail . map read . words

division :: Int -> String
division x | x >= 1900 = "Division 1" | x >= 1600 = "Division 2" | x >= 1400 = "Division 3" | otherwise = "Division 4"

main :: IO()
main = interact $ show . unlines . map division . tail . map read . words

division :: Int -> String
division x | x >= 1900 = "Division 1\n" | x >= 1600 = "Division 2\n" | x >= 1400 = "Division 3\n" | otherwise = "Division 4\n"

main :: IO()
main = interact $ unlines . map show . map division . tail . map read . words

import Control.Monad

getDiv :: Integer -> String
getDiv x = if (x <= 1399) then "Division 4" else if (x <= 1599) then "Division 3" else if (x <= 1899) then "Division 2" else "Division 1"

main :: IO ()
main = do
    t <- getLine
    nrs <- replicateM (read t) getLine
    mapM_ print $ map getDiv $ map (read :: String -> Integer) nrs

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

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

readIntArr :: IO [Int]
readIntArr = do
  arr <- words <$> getLine
  pure $ map parseInt arr

calc :: Int -> String
calc x
  | x < 1400 = "Division 4"
  | x < 1600 = "Division 3"
  | x < 1900 = "Division 2"
  | otherwise = "Division 1"

solve :: IO ()
solve = do
  rating <- readInt
  print $ calc rating

for :: Int -> IO () -> IO ()
for 0 _ = pure ()
for i f = do
  f
  for (i - 1) f

main :: IO ()
main = do
  n <- readInt
  for n solve


import qualified Data.List as L
getRoute a b c i = (sum (take i a)) + (sum (drop i b)) + (c !! i)
main=do
  w0 <-getLine
  let n=read w0::Int
  w1 <- getLine
  let a=[read n::Int|n<-words(w1)]
  w2 <- getLine
  let b=[read n::Int|n<-words(w2)]
  w3 <- getLine
  let c=[read n::Int|n<-words(w3)]
  let s=L.sort $ map (getRoute a b c) [0..(n-1)]
  print ((s !! 0)+(s !! 1))

import Data.List

readInts = getLine >>= (\line -> return (map read (words line) :: [Int]))

cross a1 a2 n [] 0 = []
cross a1 a2 n (r : rs) x = (sum (take c a1) + sum (drop c a2) + r) : (cross a1 a2 n rs (x - 1)) where c = n - x

main = do
  n <- (readInts >>= (\l -> return (head l)))
  a1 <- readInts
  a2 <- readInts
  s <- readInts
  let x : y : _ = sort (cross a1 a2 n s n)
  putStrLn (show (x + y))

import Data.List

main :: IO()
main = print . solve . map read . words =<< getContents

solve :: [Int] -> Int
solve a = let n = head a
              r1 = drop 1 a
              a1 = take (n - 1) r1
              r2 = drop (n - 1) r1
              a2 = take (n - 1) r2
              b = drop (n - 1) r2
          in solve' n a1 a2 b

solve' :: Int -> [Int] -> [Int] -> [Int] -> Int
solve' n a1 a2 b = let p = sort $ map (dist a1 a2 b) [0..(n-1)]
                   in (head p) + (p !! 1)

dist :: [Int] -> [Int] -> [Int] -> Int -> Int
dist a1 a2 b i = (sum (take i a1)) + (sum (drop i a2)) + (b !! i)

main = do
    n <- readLn :: IO Int
    r1 <- fmap ((map read) . words) getLine :: IO [Int]
    r2 <- fmap ((map read) . words) getLine :: IO [Int]
    imd <- fmap ((map read) . words) getLine :: IO [Int]
    let p1 = scanl (+) 0 r1
        p2 = scanr (+) 0 r2
        list = zip (go p1 p2 imd) [1..]
        ans = minimum [x+y | (x,n1) <-list , (y,n2)<-list , n1/=n2]
    print ans

go p1 p2 imd = zipWith3 (\x y z -> x+y+z) p1 p2 imd


import Control.Monad (forM_)
import Data.List (sortBy, findIndex)

-- fst of first time when snd >= fst
-- if snd never becomes >= fst, then snd of last item

solve :: [Int] -> [Int] -> Int
solve as bs = rez
  where z = zip as bs
        sf x y = compare (fst y) (fst x)
        scf x y = (fst y, snd x + snd y)
        scl = tail . scanl scf (0, 0) $ sortBy sf z
        mi = findIndex (\(x, y) -> y > x) scl
        rez = case mi of
                Just i -> rez' i
                Nothing -> snd $ last scl
        rez' i = if i == 0 then fst (head scl) else max (snd $ scl !! (i - 1)) (fst (scl !! i))

main :: IO ()
main = getLine >>= pure . read >>= \t -> forM_ [1..t] . const $ getLine >> do
         as <- pure . map read . words =<< getLine
         bs <- pure . map read . words =<< getLine
         putStrLn . show $ solve as bs

import Control.Monad (forM_)
import Data.List (sortBy, genericSplitAt)

-- * Types and utilities

-- | A splitting strategy.
data Splitter a = Splitter { delimiter        :: Delimiter a
                               -- ^ What delimiter to split on
                           , delimPolicy      :: DelimPolicy
                               -- ^ What to do with delimiters (drop
                               --   from output, keep as separate
                               --   elements in output, or merge with
                               --   previous or following chunks)
                           , condensePolicy   :: CondensePolicy
                               -- ^ What to do with multiple
                               --   consecutive delimiters
                           , initBlankPolicy  :: EndPolicy
                               -- ^ Drop an initial blank?
                           , finalBlankPolicy :: EndPolicy
                               -- ^ Drop a final blank?
                           }

-- | The default splitting strategy: keep delimiters in the output
--   as separate chunks, don't condense multiple consecutive
--   delimiters into one, keep initial and final blank chunks.
--   Default delimiter is the constantly false predicate.
--
--   Note that 'defaultSplitter' should normally not be used; use
--   'oneOf', 'onSublist', or 'whenElt' instead, which are the same as
--   the 'defaultSplitter' with just the delimiter overridden.
--
--   The 'defaultSplitter' strategy with any delimiter gives a
--   maximally information-preserving splitting strategy, in the sense
--   that (a) taking the 'concat' of the output yields the original
--   list, and (b) given only the output list, we can reconstruct a
--   'Splitter' which would produce the same output list again given
--   the original input list.  This default strategy can be overridden
--   to allow discarding various sorts of information.
defaultSplitter :: Splitter a
defaultSplitter = Splitter { delimiter        = Delimiter [const False]
                           , delimPolicy      = Keep
                           , condensePolicy   = KeepBlankFields
                           , initBlankPolicy  = KeepBlank
                           , finalBlankPolicy = KeepBlank
                           }

-- | A delimiter is a list of predicates on elements, matched by some
--   contiguous subsequence of a list.
newtype Delimiter a = Delimiter [a -> Bool]

-- | Try to match a delimiter at the start of a list, either failing
--   or decomposing the list into the portion which matched the delimiter
--   and the remainder.
matchDelim :: Delimiter a -> [a] -> Maybe ([a],[a])
matchDelim (Delimiter []) xs = Just ([],xs)
matchDelim (Delimiter _)  [] = Nothing
matchDelim (Delimiter (p:ps)) (x:xs)
  | p x       = matchDelim (Delimiter ps) xs >>= \(h,t) -> Just (x:h,t)
  | otherwise = Nothing

-- | What to do with delimiters?
data DelimPolicy = Drop      -- ^ Drop delimiters from the output.
                 | Keep      -- ^ Keep delimiters as separate chunks
                             --   of the output.
                 | KeepLeft  -- ^ Keep delimiters in the output,
                             --   prepending them to the following
                             --   chunk.
                 | KeepRight -- ^ Keep delimiters in the output,
                             --   appending them to the previous chunk.
  deriving (Eq, Show)

-- | What to do with multiple consecutive delimiters?
data CondensePolicy = Condense         -- ^ Condense into a single delimiter.
                    | DropBlankFields  -- ^ Keep consecutive
                                       --   delimiters separate, but
                                       --   don't insert blank chunks in
                                       --   between them.
                    | KeepBlankFields  -- ^ Insert blank chunks
                                       --   between consecutive
                                       --   delimiters.
  deriving (Eq, Show)

-- | What to do with a blank chunk at either end of the list
--   (/i.e./ when the list begins or ends with a delimiter).
data EndPolicy = DropBlank | KeepBlank
  deriving (Eq, Show)

-- | Tag chunks as delimiters or text.
data Chunk a = Delim [a] | Text [a]
  deriving (Show, Eq)

-- | Internal representation of a split list that tracks which pieces
--   are delimiters and which aren't.
type SplitList a = [Chunk a]

-- | Untag a 'Chunk'.
fromElem :: Chunk a -> [a]
fromElem (Text as) = as
fromElem (Delim as) = as

-- | Test whether a 'Chunk' is a delimiter.
isDelim :: Chunk a -> Bool
isDelim (Delim _) = True
isDelim _ = False

-- | Test whether a 'Chunk' is text.
isText :: Chunk a -> Bool
isText (Text _) = True
isText _ = False

-- * Implementation

-- | Given a delimiter to use, split a list into an internal
--   representation with chunks tagged as delimiters or text.  This
--   transformation is lossless; in particular,
--
-- @
--   'concatMap' 'fromElem' ('splitInternal' d l) == l.
-- @
splitInternal :: Delimiter a -> [a] -> SplitList a
splitInternal _ [] = []
splitInternal d xxs
  | null xs   = toSplitList match
  | otherwise = Text xs : toSplitList match
 where
  (xs,match) = breakDelim d xxs

  toSplitList Nothing             = []
  toSplitList (Just ([],r:rs))    = Delim [] : Text [r] : splitInternal d rs
  toSplitList (Just (delim,rest)) = Delim delim : splitInternal d rest

breakDelim :: Delimiter a -> [a] -> ([a],Maybe ([a],[a]))
breakDelim (Delimiter []) xs         = ([],Just ([],xs))
breakDelim _              []         = ([],Nothing)
breakDelim d              xxs@(x:xs) =
  case matchDelim d xxs of
      Nothing    -> let (ys,match) = breakDelim d xs in (x:ys,match)
      Just match -> ([], Just match)

-- | Given a split list in the internal tagged representation, produce
--   a new internal tagged representation corresponding to the final
--   output, according to the strategy defined by the given
--   'Splitter'.
postProcess :: Splitter a -> SplitList a -> SplitList a
postProcess s = dropFinal (finalBlankPolicy s)
              . dropInitial (initBlankPolicy s)
              . doMerge (delimPolicy s)
              . doDrop (delimPolicy s)
              . insertBlanks (condensePolicy s)
              . doCondense (condensePolicy s)

-- | Drop delimiters if the 'DelimPolicy' is 'Drop'.
doDrop :: DelimPolicy -> SplitList a -> SplitList a
doDrop Drop l = [ c | c@(Text _) <- l ]
doDrop _ l = l

-- | Condense multiple consecutive delimiters into one if the
--   'CondensePolicy' is 'Condense'.
doCondense :: CondensePolicy -> SplitList a -> SplitList a
doCondense Condense ls = condense' ls
  where condense' [] = []
        condense' (c@(Text _) : l) = c : condense' l
        condense' l = (Delim $ concatMap fromElem ds) : condense' rest
          where (ds,rest) = span isDelim l
doCondense _ ls = ls

-- | Insert blank chunks between any remaining consecutive delimiters
--   (unless the condense policy is 'DropBlankFields'), and at the
--   beginning or end if the first or last element is a delimiter.
insertBlanks :: CondensePolicy -> SplitList a -> SplitList a
insertBlanks _ [] = [Text []]
insertBlanks cp (d@(Delim _) : l) = Text [] : insertBlanks' cp (d:l)
insertBlanks cp l = insertBlanks' cp l

-- | Insert blank chunks between consecutive delimiters.
insertBlanks' :: CondensePolicy -> SplitList a -> SplitList a
insertBlanks' _ [] = []
insertBlanks' cp@DropBlankFields (d1@(Delim _) : d2@(Delim _) : l)
  = d1           : insertBlanks' cp (d2:l)
insertBlanks' cp (d1@(Delim _) : d2@(Delim _) : l)
  = d1 : Text [] : insertBlanks' cp (d2:l)
insertBlanks' _ [d@(Delim _)] = [d, Text []]
insertBlanks' cp (c : l) = c : insertBlanks' cp l

-- | Merge delimiters into adjacent chunks according to the 'DelimPolicy'.
doMerge :: DelimPolicy -> SplitList a -> SplitList a
doMerge KeepLeft = mergeLeft
doMerge KeepRight = mergeRight
doMerge _ = id

-- | Merge delimiters with adjacent chunks to the right (yes, that's
--   not a typo: the delimiters should end up on the left of the
--   chunks, so they are merged with chunks to their right).
mergeLeft :: SplitList a -> SplitList a
mergeLeft [] = []
mergeLeft ((Delim d) : (Text c) : l) = Text (d++c) : mergeLeft l
mergeLeft (c : l) = c : mergeLeft l

-- | Merge delimiters with adjacent chunks to the left.
mergeRight :: SplitList a -> SplitList a
mergeRight [] = []
-- below fanciness is with the goal of laziness: we want to start returning
-- stuff before we've necessarily discovered a delimiter, in case we're
-- processing some infinite list with no delimiter
mergeRight ((Text c) : l) = Text (c++d) : mergeRight lTail
  where (d, lTail) = case l of
                     Delim d' : l' -> (d', l')
                     _ -> ([], l)
mergeRight (c : l) = c : mergeRight l

-- | Drop an initial blank chunk according to the given 'EndPolicy'.
dropInitial :: EndPolicy -> SplitList a -> SplitList a
dropInitial DropBlank (Text [] : l) = l
dropInitial _ l = l

-- | Drop a final blank chunk according to the given 'EndPolicy'.
dropFinal :: EndPolicy -> SplitList a -> SplitList a
dropFinal _         [] = []
dropFinal DropBlank l  = dropFinal' l
  where dropFinal' []        = []
        dropFinal' [Text []] = []
        dropFinal' (x:xs)    = x:dropFinal' xs
dropFinal _         l  = l

-- * Combinators

-- | Split a list according to the given splitting strategy.  This is
--   how to \"run\" a 'Splitter' that has been built using the other
--   combinators.
split :: Splitter a -> [a] -> [[a]]
split s = map fromElem . postProcess s . splitInternal (delimiter s)

-- ** Basic strategies
--
-- $ All these basic strategies have the same parameters as the
-- 'defaultSplitter' except for the delimiters.

-- | A splitting strategy that splits on any one of the given
--   elements.  For example:
--
-- > split (oneOf "xyz") "aazbxyzcxd" == ["aa","z","b","x","","y","","z","c","x","d"]
oneOf :: Eq a => [a] -> Splitter a
oneOf elts = defaultSplitter { delimiter = Delimiter [(`elem` elts)] }

-- | A splitting strategy that splits on the given list, when it is
--   encountered as an exact subsequence.  For example:
--
-- > split (onSublist "xyz") "aazbxyzcxd" == ["aazb","xyz","cxd"]
--
--   Note that splitting on the empty list is a special case, which
--   splits just before every element of the list being split.  For example:
--
-- > split (onSublist "") "abc" == ["","","a","","b","","c"]
-- > split (dropDelims . dropBlanks $ onSublist "") "abc" == ["a","b","c"]
--
--   However, if you want to break a list into singleton elements like
--   this, you are better off using @'chunksOf' 1@, or better yet,
--   @'map' (:[])@.
onSublist :: Eq a => [a] -> Splitter a
onSublist lst = defaultSplitter { delimiter = Delimiter (map (==) lst) }

-- | A splitting strategy that splits on any elements that satisfy the
--   given predicate.  For example:
--
-- > split (whenElt (<0)) [2,4,-3,6,-9,1] == [[2,4],[-3],[6],[-9],[1]]
whenElt :: (a -> Bool) -> Splitter a
whenElt p = defaultSplitter { delimiter = Delimiter [p] }

-- ** Strategy transformers

-- | Drop delimiters from the output (the default is to keep
--   them). For example,
--
-- > split (oneOf ":") "a:b:c" == ["a", ":", "b", ":", "c"]
-- > split (dropDelims $ oneOf ":") "a:b:c" == ["a", "b", "c"]
dropDelims :: Splitter a -> Splitter a
dropDelims s = s { delimPolicy = Drop }

-- | Keep delimiters in the output by prepending them to adjacent
--   chunks.  For example:
--
-- > split (keepDelimsL $ oneOf "xyz") "aazbxyzcxd" == ["aa","zb","x","y","zc","xd"]
keepDelimsL :: Splitter a -> Splitter a
keepDelimsL s = s { delimPolicy = KeepLeft }

-- | Keep delimiters in the output by appending them to adjacent
--   chunks. For example:
--
-- > split (keepDelimsR $ oneOf "xyz") "aazbxyzcxd" == ["aaz","bx","y","z","cx","d"]
keepDelimsR :: Splitter a -> Splitter a
keepDelimsR s = s { delimPolicy = KeepRight }

-- | Condense multiple consecutive delimiters into one.  For example:
--
-- > split (condense $ oneOf "xyz") "aazbxyzcxd" == ["aa","z","b","xyz","c","x","d"]
-- > split (dropDelims $ oneOf "xyz") "aazbxyzcxd" == ["aa","b","","","c","d"]
-- > split (condense . dropDelims $ oneOf "xyz") "aazbxyzcxd" == ["aa","b","c","d"]
condense :: Splitter a -> Splitter a
condense s = s { condensePolicy = Condense }

-- | Don't generate a blank chunk if there is a delimiter at the
--   beginning.  For example:
--
-- > split (oneOf ":") ":a:b" == ["",":","a",":","b"]
-- > split (dropInitBlank $ oneOf ":") ":a:b" == [":","a",":","b"]
dropInitBlank :: Splitter a -> Splitter a
dropInitBlank s = s { initBlankPolicy = DropBlank }

-- | Don't generate a blank chunk if there is a delimiter at the end.
--   For example:
--
-- > split (oneOf ":") "a:b:" == ["a",":","b",":",""]
-- > split (dropFinalBlank $ oneOf ":") "a:b:" == ["a",":","b",":"]
dropFinalBlank :: Splitter a -> Splitter a
dropFinalBlank s = s { finalBlankPolicy = DropBlank }

-- | Don't generate blank chunks between consecutive delimiters.
--   For example:
--
-- > split (oneOf ":") "::b:::a" == ["",":","",":","b",":","",":","",":","a"]
-- > split (dropInnerBlanks $ oneOf ":") "::b:::a" == ["", ":",":","b",":",":",":","a"]
dropInnerBlanks :: Splitter a -> Splitter a
dropInnerBlanks s = s { condensePolicy = DropBlankFields }

-- ** Derived combinators

-- | Drop all blank chunks from the output, and condense consecutive
--   delimiters into one.  Equivalent to @'dropInitBlank'
--   . 'dropFinalBlank' . 'condense'@.  For example:
--
-- > split (oneOf ":") "::b:::a" == ["",":","",":","b",":","",":","",":","a"]
-- > split (dropBlanks $ oneOf ":") "::b:::a" == ["::","b",":::","a"]
dropBlanks :: Splitter a -> Splitter a
dropBlanks = dropInitBlank . dropFinalBlank . condense

-- | Make a strategy that splits a list into chunks that all start
--   with the given subsequence (except possibly the first).
--   Equivalent to @'dropInitBlank' . 'keepDelimsL' . 'onSublist'@.
--   For example:
--
-- > split (startsWith "app") "applyapplicativeapplaudapproachapple" == ["apply","applicative","applaud","approach","apple"]
startsWith :: Eq a => [a] -> Splitter a
startsWith = dropInitBlank . keepDelimsL . onSublist

-- | Make a strategy that splits a list into chunks that all start
--   with one of the given elements (except possibly the first).
--   Equivalent to @'dropInitBlank' . 'keepDelimsL' . 'oneOf'@.  For
--   example:
--
-- > split (startsWithOneOf ['A'..'Z']) "ACamelCaseIdentifier" == ["A","Camel","Case","Identifier"]
startsWithOneOf :: Eq a => [a] -> Splitter a
startsWithOneOf = dropInitBlank . keepDelimsL . oneOf

-- | Make a strategy that splits a list into chunks that all end with
--   the given subsequence, except possibly the last.  Equivalent to
--   @'dropFinalBlank' . 'keepDelimsR' . 'onSublist'@.  For example:
--
-- > split (endsWith "ly") "happilyslowlygnarlylily" == ["happily","slowly","gnarly","lily"]
endsWith :: Eq a => [a] -> Splitter a
endsWith = dropFinalBlank . keepDelimsR . onSublist

-- | Make a strategy that splits a list into chunks that all end with
--   one of the given elements, except possibly the last.  Equivalent
--   to @'dropFinalBlank' . 'keepDelimsR' . 'oneOf'@.  For example:
--
-- > split (condense $ endsWithOneOf ".,?! ") "Hi, there!  How are you?" == ["Hi, ","there!  ","How ","are ","you?"]
endsWithOneOf :: Eq a => [a] -> Splitter a
endsWithOneOf = dropFinalBlank . keepDelimsR . oneOf

-- ** Convenience functions
--
-- These functions implement some common splitting strategies.  Note
-- that all of the functions in this section drop delimiters from
-- the final output, since that is a more common use case even
-- though it is not the default.

-- | Split on any of the given elements.  Equivalent to @'split'
--   . 'dropDelims' . 'oneOf'@.  For example:
--
-- > splitOneOf ";.," "foo,bar;baz.glurk" == ["foo","bar","baz","glurk"]
splitOneOf :: Eq a => [a] -> [a] -> [[a]]
splitOneOf = split . dropDelims . oneOf

-- | Split on the given sublist.  Equivalent to @'split'
--   . 'dropDelims' . 'onSublist'@.  For example:
--
-- > splitOn ".." "a..b...c....d.." == ["a","b",".c","","d",""]
--
--   In some parsing combinator frameworks this is also known as
--   @sepBy@.
--
--   Note that this is the right inverse of the 'Data.List.intercalate' function
--   from "Data.List", that is,
--
--   > intercalate x . splitOn x === id
--
--   @'splitOn' x . 'Data.List.intercalate' x@ is the identity on
--   certain lists, but it is tricky to state the precise conditions
--   under which this holds.  (For example, it is not enough to say
--   that @x@ does not occur in any elements of the input list.
--   Working out why is left as an exercise for the reader.)
splitOn :: Eq a => [a] -> [a] -> [[a]]
splitOn   = split . dropDelims . onSublist

-- | Split on elements satisfying the given predicate.  Equivalent to
--   @'split' . 'dropDelims' . 'whenElt'@.  For example:
--
-- > splitWhen (<0) [1,3,-4,5,7,-9,0,2] == [[1,3],[5,7],[0,2]]
splitWhen :: (a -> Bool) -> [a] -> [[a]]
splitWhen = split . dropDelims . whenElt

{-# DEPRECATED sepBy "Use splitOn." #-}
sepBy :: Eq a => [a] -> [a] -> [[a]]
sepBy = splitOn

{-# DEPRECATED sepByOneOf "Use splitOneOf." #-}
sepByOneOf :: Eq a => [a] -> [a] -> [[a]]
sepByOneOf = splitOneOf

-- | Split into chunks terminated by the given subsequence.
--   Equivalent to @'split' . 'dropFinalBlank' . 'dropDelims'
--   . 'onSublist'@.  For example:
--
-- > endBy ";" "foo;bar;baz;" == ["foo","bar","baz"]
--
--   Note also that the 'lines' function from "Data.List" is equivalent
--   to @'endBy' \"\\n\"@.
endBy :: Eq a => [a] -> [a] -> [[a]]
endBy = split . dropFinalBlank . dropDelims . onSublist

-- | Split into chunks terminated by one of the given elements.
--   Equivalent to @'split' . 'dropFinalBlank' . 'dropDelims'
--   . 'oneOf'@. For example:
--
-- > endByOneOf ";," "foo;bar,baz;" == ["foo","bar","baz"]
endByOneOf :: Eq a => [a] -> [a] -> [[a]]
endByOneOf = split . dropFinalBlank . dropDelims . oneOf

{-# DEPRECATED unintercalate "Use splitOn." #-}
unintercalate :: Eq a => [a] -> [a] -> [[a]]
unintercalate = splitOn

-- | Split into \"words\", with word boundaries indicated by the given
--   predicate.  Satisfies @'Data.List.words' === wordsBy
--   'Data.Char.isSpace'@; equivalent to @'split' . 'dropBlanks'
--   . 'dropDelims' . 'whenElt'@.  For example:
--
-- > wordsBy (=='x') "dogxxxcatxbirdxx" == ["dog","cat","bird"]
wordsBy :: (a -> Bool) -> [a] -> [[a]]
wordsBy = split . dropBlanks . dropDelims . whenElt

-- | Split into \"lines\", with line boundaries indicated by the given
--   predicate. Satisfies @'lines' === linesBy (=='\n')@; equivalent to
--   @'split' . 'dropFinalBlank' . 'dropDelims' . 'whenElt'@.  For example:
--
-- > linesBy (=='x') "dogxxxcatxbirdxx" == ["dog","","","cat","bird",""]
linesBy :: (a -> Bool) -> [a] -> [[a]]
linesBy = split . dropFinalBlank . dropDelims . whenElt

-- * Other splitting methods

-- | Standard build function, specialized to building lists.
--
--   Usually build is given the rank-2 type
--
--   > build :: (forall b. (a -> b -> b) -> b -> b) -> [a]
--
--   but since we only use it when @(b ~ [a])@, we give it the more
--   restricted type signature in order to avoid needing a
--   non-Haskell2010 extension.
--
--   Note that the 0.1.4.3 release of this package did away with a
--   custom @build@ implementation in favor of importing one from
--   "GHC.Exts", which was (reportedly) faster for some applications.
--   However, in the interest of simplicity and complete Haskell2010
--   compliance as @split@ is being included in the Haskel Platform,
--   version 0.2.1.0 has gone back to defining @build@ manually.  This
--   is in line with @split@'s design philosophy of having efficiency
--   as a non-goal.
build :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]
build g = g (:) []

-- | @'chunksOf' n@ splits a list into length-n pieces.  The last
--   piece will be shorter if @n@ does not evenly divide the length of
--   the list.  If @n <= 0@, @'chunksOf' n l@ returns an infinite list
--   of empty lists.  For example:
--
--   Note that @'chunksOf' n []@ is @[]@, not @[[]]@.  This is
--   intentional, and is consistent with a recursive definition of
--   'chunksOf'; it satisfies the property that
--
--   @chunksOf n xs ++ chunksOf n ys == chunksOf n (xs ++ ys)@
--
--   whenever @n@ evenly divides the length of @xs@.
chunksOf :: Int -> [e] -> [[e]]
chunksOf i ls = map (take i) (build (splitter ls)) where
  splitter :: [e] -> ([e] -> a -> a) -> a -> a
  splitter [] _ n = n
  splitter l c n  = l `c` splitter (drop i l) c n

{-# DEPRECATED chunk "Use chunksOf." #-}
chunk :: Int -> [e] -> [[e]]
chunk = chunksOf

{-# DEPRECATED splitEvery "Use chunksOf." #-}
splitEvery :: Int -> [e] -> [[e]]
splitEvery = chunksOf

-- | Split a list into chunks of the given lengths. For example:
--
-- > splitPlaces [2,3,4] [1..20] == [[1,2],[3,4,5],[6,7,8,9]]
-- > splitPlaces [4,9] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]]
-- > splitPlaces [4,9,3] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]]
--
--   If the input list is longer than the total of the given lengths,
--   then the remaining elements are dropped. If the list is shorter
--   than the total of the given lengths, then the result may contain
--   fewer chunks than requested, and the last chunk may be shorter
--   than requested.
splitPlaces :: Integral a => [a] -> [e] -> [[e]]
splitPlaces is ys = build (splitPlacer is ys) where
  splitPlacer :: Integral i => [i] -> [b] -> ([b] -> t -> t) -> t -> t
  splitPlacer [] _ _ n      = n
  splitPlacer _ [] _ n      = n
  splitPlacer (l:ls) xs c n = let (x1, x2) = genericSplitAt l xs
                              in  x1 `c` splitPlacer ls x2 c n

-- | Split a list into chunks of the given lengths. Unlike
--   'splitPlaces', the output list will always be the same length as
--   the first input argument. If the input list is longer than the
--   total of the given lengths, then the remaining elements are
--   dropped. If the list is shorter than the total of the given
--   lengths, then the last several chunks will be shorter than
--   requested or empty. For example:
--
-- > splitPlacesBlanks [2,3,4] [1..20] == [[1,2],[3,4,5],[6,7,8,9]]
-- > splitPlacesBlanks [4,9] [1..10] == [[1,2,3,4],[5,6,7,8,9,10]]
-- > splitPlacesBlanks [4,9,3] [1..10] == [[1,2,3,4],[5,6,7,8,9,10],[]]
--
--   Notice the empty list in the output of the third example, which
--   differs from the behavior of 'splitPlaces'.
splitPlacesBlanks :: Integral a => [a] -> [e] -> [[e]]
splitPlacesBlanks is ys = build (splitPlacer is ys) where
  splitPlacer :: Integral i => [i] -> [b] -> ([b] -> t -> t) -> t -> t
  splitPlacer [] _ _ n      = n
  splitPlacer (l:ls) xs c n = let (x1, x2) = genericSplitAt l xs
                              in  x1 `c` splitPlacer ls x2 c n

-- | A useful recursion pattern for processing a list to produce a new
--   list, often used for \"chopping\" up the input list.  Typically
--   chop is called with some function that will consume an initial
--   prefix of the list and produce a value and the rest of the list.
--
--   For example, many common Prelude functions can be implemented in
--   terms of @chop@:
--
-- > group :: (Eq a) => [a] -> [[a]]
-- > group = chop (\ xs@(x:_) -> span (==x) xs)
-- >
-- > words :: String -> [String]
-- > words = filter (not . null) . chop (span (not . isSpace) . dropWhile isSpace)

chop :: ([a] -> (b, [a])) -> [a] -> [b]
chop _ [] = []
chop f as = b : chop f as'
  where (b, as') = f as

-- | Divides up an input list into a set of sublists, according to 'n' and 'm'
--   input specifications you provide. Each sublist will have 'n' items, and the
--   start of each sublist will be offset by 'm' items from the previous one.
--
-- > divvy 5 5 [1..20] == [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
--
--   In the case where a source list's trailing elements do no fill an entire
--   sublist, those trailing elements will be dropped.
--
-- > divvy 5 2 [1..10] == [[1,2,3,4,5],[3,4,5,6,7],[5,6,7,8,9]]
--
--   As an example, you can generate a moving average over a list of prices:
--
-- > type Prices = [Float]
-- > type AveragePrices = [Float]
-- >
-- > average :: [Float] -> Float
-- > average xs = sum xs / (fromIntegral $ length xs)
-- >
-- > simpleMovingAverage :: Prices -> AveragePrices
-- > simpleMovingAverage priceList =
-- >   map average divvyedPrices
-- >     where divvyedPrices = divvy 20 1 priceList

divvy :: Int -> Int -> [a] -> [[a]]
divvy _ _ [] = []
divvy n m lst = filter (\ws -> (n == length ws)) choppedl
  where choppedl = chop (\xs -> (take n xs , drop m xs)) lst

-- fst of first time when snd >= fst
-- if snd never becomes >= fst, then snd of last item

solve :: [Int] -> [Int] -> Int
solve as bs = if length spl == 1 then snd . last $ h else m
  where z = zip as bs
        sf x y = compare (fst y) (fst x)
        scf x y = (fst y, snd x + snd y)
        scl = tail . scanl scf (0, 0) $ sortBy sf z
        spl = split (keepDelimsL $ whenElt (\(f, s) -> s >= f)) scl
        m = max (if length h > 0 then snd . last $ h else 0) (fst . head . head $ tail spl)
        h = head spl

main :: IO ()
main = getLine >>= pure . read >>= \t -> forM_ [1..t] . const $ getLine >> do
         as <- pure . map read . words =<< getLine
         bs <- pure . map read . words =<< getLine
         putStrLn . show $ solve as bs

import Control.Arrow ((>>>))
import Data.List (sortBy)
import Data.Ord (comparing)

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

process :: [[Integer]] -> [Integer]
process [] = []
process (_:as:bs:xss) = solve as bs : process xss

solve :: [Integer] -> [Integer] -> Integer
solve as bs = minimum costs
  where
    (as', bs') = unzip . sortBy (comparing fst) $ zip as bs
    costs = zipWith max (scanl max 0 as') (scanr (+) 0 bs')

import Control.Arrow ((>>>))
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List (sortBy)
import Data.Maybe (fromMaybe)
import Data.Ord (comparing)

main :: IO ()
main =
  C.interact $
  C.lines >>>
  drop 1 >>>
  map (C.words >>> map readInt) >>>
  process >>> map (show >>> C.pack) >>> C.unlines
  where
    readInt = C.readInt >>> fromMaybe undefined >>> fst >>> fromIntegral

process :: [[Integer]] -> [Integer]
process [] = []
process (_:as:bs:xss) = solve as bs : process xss

solve :: [Integer] -> [Integer] -> Integer
solve as bs = minimum costs
  where
    (as', bs') = unzip . sortBy (comparing fst) $ zip as bs
    costs = zipWith max (scanl max 0 as') (scanr (+) 0 bs')

import Control.Arrow ((>>>))
import Data.List (sortBy)
import Data.Ord (comparing)

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

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

solve :: [Int] -> [Int] -> Int
solve as bs = minimum costs
  where
    (as', bs') = unzip . sortBy (comparing fst) $ zip as bs
    costs = zipWith max (scanl max 0 as') (scanr (+) 0 bs')

import Control.Monad (forM_)
import Data.List (sortBy)

solve :: String -> String -> Int
solve as' bs' = if length fl == 0 then fst . head $ sc else snd . last $ fl
  where as = l as'
	bs = l bs'
	l = map read . words
	ts' = zip as bs
	ts = reverse $ sortBy sf ts'
	sf x y = compare (fst x) (fst y)
	sc = tail $ scanl (\(ox, oy) (nx, ny) -> (nx, oy + ny)) (1, 0) ts
	fl = filter (\(x, y) -> x >= y) sc

main :: IO ()
main = do
  t <- pure . read =<< getLine
  forM_ [1..t] . const $ getLine >> getLine >>= \as -> do
	bs <- getLine
	putStrLn . show . solve as $ bs

import Control.Monad (forM_)
import Data.List (sortBy)

-- fst of first time when snd >= fst
-- if snd never becomes >= fst, then snd of last item

solve :: [Int] -> [Int] -> Int
solve as bs = if length fl == 0 then snd $ last scl else fst $ head fl
  where z = zip as bs
        sf x y = compare (fst y) (fst x)
        scf x y = (fst y, snd x + snd y)
        scl = tail . scanl scf (0, 0) $ sortBy sf z
        fl = filter (\(f, s) -> s >= f) scl

main :: IO ()
main = getLine >>= pure . read >>= \t -> forM_ [1..t] . const $ getLine >> do
         as <- pure . map read . words =<< getLine
         bs <- pure . map read . words =<< getLine
         putStrLn . show $ solve as bs


import Array
main = interact (ans)
ans theInput = answer where
  theLines = lines theInput
  line0 = words $ head $ theLines
  n = read ( line0 !! 0 ) ::Int
  m = read ( line0 !! 1 ) ::Int
  k0 = read ( line0 !! 2 ) ::Integer
  rMax = div (min n m) 2
  k = if k0 > 5000000 then 5000000 else read ( line0 !! 2 ) ::Int
  theMap = array ((1,1),(n,m)) [((i,j),(take n (tail theLines))!!(i-1)!!(j-1)=='*')|i<-[1..n],j<-[1..m]]
  centerOfCross = [(r,i,j)|r<-[1..rMax],i<-[1+r..n-r],j<-[1+r..m-r],check i j r] ++ repeat (-1,-1,-1) where
    check i j r = and [ ce, up, lo, le, ri ] where
      ce = theMap ! (i,j)
      up = theMap ! (i-r,j)
      lo = theMap ! (i+r,j)
      le = theMap ! (i,j-r)
      ri = theMap ! (i,j+r)
  ans1 = centerOfCross !! (k-1)
  answer = if ans1==(-1,-1,-1)
              then "-1"
              else unlines $ map unwords ans0 where
                ans0 = [ce,up,lo,le,ri]
                ce = [show i,show j]
                up = [show (i-r),show j]
                lo = [show (i+r),show j]
                le = [show i,show (j-r)]
                ri = [show i,show (j+r)]
                (r,i,j) = ans1

import Control.Arrow
import Control.Monad
import Data.Array

main = do
	[n, m, k] <- fmap (map read . words) getLine
	a <- replicateM n getLine
	putStr $ head $ (++["-1"]) $ drop (k - 1) $ gao n m $ listArray ((1,1),(n,m)) $ concat a

gao n m a = [unlines $ map (\(i, j) -> show i ++ " " ++ show j) z |
	r <- [1 .. min n m - 1],
	s <- [[id *** id, flip (-) r *** id, (+r) *** id, id *** flip (-) r, id *** (+r)]],
	x <- [r + 1 .. n - r],
	y <- [r + 1 .. m - r],
	a!(x, y) == '*',
	z <- [map (\k -> k (x, y)) s],
	and [a!(i, j) == '*' | (i, j) <- z]]

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import Text.Printf
import Data.IORef
import Data.Array.Unboxed
import System.Exit

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : m : k : _ <- readData
  cs <- concat <$> replicateM n getLine
  let b = ((1, 1), (n , m))
      table = listArray b cs :: UArray (Int, Int) Char
  c <- newIORef 1 :: IO (IORef Int)
  let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]
  forM_ ([1 .. min n m `quot` 2]) $ \d -> do
    forM_ [1 + d .. n - d] $ \i -> do
      forM_ [1 + d .. m - d] $ \j -> do
        let idx = (i, j)
        when (table ! idx == '*') $ do
          let xs =  getOthers idx d
          when ((&&) <$> all (inRange b) <*> all ((== '*') . (table !)) $ xs) $ do
            count <- readIORef c
            writeIORef c (count + 1)
            when (count == k) $ do
              forM_ (idx : xs) $ \(i', j') -> do
                printf "%d %d\n" i' j'
              exitSuccess
  printf "-1\n"

{-
7 7 4
.***...
.***...
.***...
*******
...*...
...*...
...*...
-}

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
-- import Control.Arrow
import Data.List
-- import Data.Maybe
import Data.Ord
-- import Data.Char
-- import Data.Function
-- import qualified Data.Map as Map
-- import qualified Data.Set as Set
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Text.Printf
import Data.Array.Unboxed

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : m : k : _ <- readData
  cs <- concat <$> replicateM n getLine
  let b = ((1, 1), (n , m))
      table = listArray b cs :: UArray (Int, Int) Char
      candidates = do
        i <- [1 .. n]
        j <- [1 .. m]
        let x = min i (n - i)
            y = min j (m - j)
            t = min x y
            getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]
        d <- [t, t - 1 .. 1]
        let xs = getOthers (i, j) d
        guard $ all (inRange b) xs
        guard $ all ((== '*') . (table !)) xs
        return $ (i, j) : xs
  case () of
    _ | length candidates < k -> print (-1)
      | otherwise             -> do
          forM_ (candidates !! (k - 1)) $ \(i, j) -> do
            printf "%d %d\n" i j

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
-- import Control.Arrow
import Data.List
-- import Data.Maybe
import Data.Ord
-- import Data.Char
-- import Data.Function
-- import qualified Data.Map as Map
-- import qualified Data.Set as Set
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Text.Printf
import Data.Array.Unboxed

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : m : k : _ <- readData
  cs <- concat <$> replicateM n getLine
  let b = ((1, 1), (n , m))
      table = listArray b cs :: UArray (Int, Int) Char
      candidates = do
        i <- [1 .. n]
        j <- [1 .. m]
        let x = min i (n - i)
            y = min j (m - j)
            t = min x y
            getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]
        d <- [1 .. t]
        let xs = getOthers (i, j) d
        guard $ all (inRange b) xs
        guard $ all ((== '*') . (table !)) xs
        return $ (i, j) : xs
  case () of
    _ | length candidates < k -> print (-1)
      | otherwise             -> do
          forM_ (candidates !! (k - 1)) $ \(i, j) -> do
            printf "%d %d\n" i j

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
-- import Control.Arrow
import Data.List
-- import Data.Maybe
import Data.Ord
-- import Data.Char
-- import Data.Function
-- import qualified Data.Map as Map
-- import qualified Data.Set as Set
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Text.Printf
import Data.Array.Unboxed

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : m : k : _ <- readData
  cs <- concat <$> replicateM n getLine
  let b = ((1, 1), (n , m))
      table = listArray b cs :: UArray (Int, Int) Char
      candidates = do
        i <- [1 .. n]
        j <- [1 .. m]
        let x = min i (n - i)
            y = min j (m - j)
            t = min x y
            getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]
        d <- [t .. 1]
        let xs = getOthers (i, j) d
        guard $ all (inRange b) xs
        guard $ all ((== '*') . (table !)) xs
        return $ (i, j) : xs
  case () of
    _ | length candidates < k -> print (-1)
      | otherwise             -> do
          forM_ (candidates !! (k - 1)) $ \(i, j) -> do
            printf "%d %d\n" i j

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import Text.Printf
import Data.IORef
import Data.Array.Unboxed
import System.Exit

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : m : k : _ <- readData
  cs <- concat <$> replicateM n getLine
  let b = ((1, 1), (n , m))
      table = listArray b cs :: UArray (Int, Int) Char
  c <- newIORef 1 :: IO (IORef Int)
  let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]
  forM_ (range b) $ \idx -> do
    when (table ! idx == '*') $ do
      forM_ (takeWhile (all (inRange b)) $ map (getOthers idx) [1 ..]) $ \xs -> do
        when (all ((== '*') . (table !)) xs) $ do
          count <- readIORef c
          writeIORef c (count + 1)
          when (count == k) $ do
            forM_ (idx : xs) $ \(i, j) -> do
              printf "%d %d\n" i j
            exitSuccess
  printf "-1\n"

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import Text.Printf
import Data.IORef
import Data.Array.Unboxed
import System.Exit

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : m : k : _ <- readData
  cs <- concat <$> replicateM n getLine
  let b = ((1, 1), (n , m))
      table = listArray b cs :: UArray (Int, Int) Char
  c <- newIORef 1 :: IO (IORef Int)
  forM_ (range b) $ \(i, j) -> do
    let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]
    forM_ (takeWhile (all (inRange b)) $ map (getOthers (i, j)) [1 ..]) $ \xs -> do
      when (all ((== '*') . (table !)) xs) $ do
        count <- readIORef c
        writeIORef c (count + 1)
        when (count == k) $ do
          forM_ ((i, j) : xs) $ \(i', j') -> do
            printf "%d %d\n" i' j'
          exitSuccess
  printf "-1\n"

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import Text.Printf
import Data.IORef
import Data.Array.Unboxed
import System.Exit
{-
7 7 4
.***...
.***...
.***...
*******
...*...
...*...
...*...
-}

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : m : k : _ <- readData
  cs <- concat <$> replicateM n getLine
  let b = ((1, 1), (n , m))
      table = listArray b cs :: UArray (Int, Int) Char
  c <- newIORef 1 :: IO (IORef Int)
  let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]
  forM_ (range b) $ \idx -> do
    when (table ! idx == '*') $ do
      let t = min n m `quot` 2 + 1
      forM_ (filter (all (inRange b)) $ map (getOthers idx) [1 .. t]) $ \xs -> do
        when (all ((== '*') . (table !)) xs) $ do
          count <- readIORef c
          writeIORef c (count + 1)
          when (count == k) $ do
            forM_ (idx : xs) $ \(i, j) -> do
              printf "%d %d\n" i j
            exitSuccess
  printf "-1\n"

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import Text.Printf
import Data.IORef
import Data.Array.Unboxed
import System.Exit

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
  n : m : k : _ <- readData
  cs <- concat <$> replicateM n getLine
  let b = ((1, 1), (n , m))
      table = listArray b cs :: UArray (Int, Int) Char
  c <- newIORef 1 :: IO (IORef Int)
  let getOthers (i, j) d = [(i - d, j), (i + d, j), (i, j - d), (i, j + d)]
  forM_ (range b) $ \(i, j) -> do
    forM_ (takeWhile (all (inRange b)) $ map (getOthers (i, j)) [1 ..]) $ \xs -> do
      when (all ((== '*') . (table !)) xs) $ do
        count <- readIORef c
        writeIORef c (count + 1)
        when (count == k) $ do
          forM_ ((i, j) : xs) $ \(i', j') -> do
            printf "%d %d\n" i' j'
          exitSuccess
  printf "-1\n"

{-
  forM_ (range b) $ \idx -> do
    when (table ! idx == '*') $ do
      forM_ (takeWhile (all (inRange b)) $ map (getOthers idx) [1 ..]) $ \xs -> do
        when (all ((== '*') . (table !)) xs) $ do
          count <- readIORef c
          writeIORef c (count + 1)
          when (count == k) $ do
            forM_ (idx : xs) $ \(i, j) -> do
              printf "%d %d\n" i j
            exitSuccess
  printf "-1\n"
-}

import Array
main = interact (ans)
ans theInput = answer where
  theLines = lines theInput
  line0 = words $ head $ theLines
  n = read ( line0 !! 0 ) ::Int
  m = read ( line0 !! 1 ) ::Int
  k0 = read ( line0 !! 2 ) ::Integer
  rMax = div (min n m) 2
  k = if k0 > 5000000 then 5000000 else read ( line0 !! 2 ) ::Int
  theMap = array ((1,1),(n,m)) [((i,j),(take n (tail theLines))!!(i-1)!!(j-1)=='*')|i<-[1..n],j<-[1..m]]
  centerOfCross = [(r,i,j)|r<-[1..rMax],i<-[1+r..n-r],j<-[1+r..m-r],check i j r] ++ repeat (-1,-1,-1) where
    check i j r = and [ ce, up, lo, le, ri ] where
      ce = theMap ! (i,j)
      up = theMap ! (i-r,j)
      lo = theMap ! (i+r,j)
      le = theMap ! (i,j-r)
      ri = theMap ! (i,j+r)
  ans1 = centerOfCross !! (k-1)
  answer = if ans1==(-1,-1,-1)
              then "-1"
              else unlines $ map unwords ans0 where
                ans0 = [ce,up,lo,le,ri]
                ce = [show (i+1),show (j+1)]
                up = [show (i-r+1),show (j+1)]
                lo = [show (i+r+1),show (j+1)]
                le = [show (i+1),show (j-r+1)]
                ri = [show (i+1),show (j+r+1)]
                (r,i,j) = ans1


a#b=(min a b,max a b)
s([x,y,v,w]:[n]:t)=filter b$[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=x#v;(u,d)=y#w;b(x,y)=all(\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t
main=interact$show.length.s.map(map read.words).lines

{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad

main = do
  [x1 :: Int, y1, x2, y2] <- (liftM (map read)) . (liftM words) $ getLine
  let generals = [(x1, y) | y <- [(min y1 y2) .. (max y1 y2)]] ++
                 [(x2, y) | y <- [(min y1 y2) .. (max y1 y2)]] ++
                 [(x, y1) | x <- [(min x1 x2 + 1) .. (max x1 x2 - 1)]] ++
                 [(x, y2) | x <- [(min x1 x2 + 1) .. (max x1 x2 - 1)]]
  n <- (liftM read) getLine
  heaters <- replicateM n ((liftM (\[x, y, r] -> (read x, read y, read r))) . (liftM words) $ getLine)
  putStrLn . show . length $
    filter (\(x, y) -> all (\(hx, hy, r) -> (hx - x)*(hx - x) + (hy - y)*(hy - y) > r*r)
                           heaters)
           generals

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# OPTIONS_GHC -O3 #-}

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
-- import Data.Array
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

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

main = do
  [xa, ya, xb, yb] <- getInts
  n <- readLn
  cs <- replicateM n getInts

  let
    [xa', xb'] = sort [xa, xb]
    [ya', yb'] = sort [ya, yb]

    r = length $ filter out $ [(x, ya') | x <- [xa'..xb'-1]] ++ [(xb', y) | y <- [ya'..yb'-1]] ++ [(x, yb') | x <- [xa'+1..xb']] ++ [(xa', y) | y <- [ya'+1..yb']]
      where
        out (x, y) = all (\[xx, yy, rr] -> (xx-x)^2 + (yy-y)^2 > rr^2) cs

  print r

main = interact $ show . solve . input

input :: String -> ([Int], [[Int]])
input str = (coords, circles) where
    circles = map (\xs -> map read xs) (map words ls)
    coords = map read (words cstr)
    (cstr:_:ls) = lines str

solve ([xa, ya, xb, yb], circles) = length (filter (\xy -> all (`outer` xy) circles) coords) where
    [x0, y0, r] `outer` (x, y) = (dx*dx + dy*dy) > (r*r) where
        dx = x - x0
        dy = y - y0
    coords =
        [(x, y) | x <- [xa], y <- ys] ++
        [(x, y) | x <- [xb], y <- ys] ++
        [(x, y) | x <- xs, y <- [ya]] ++
        [(x, y) | x <- xs, y <- [yb]]
    xs = let mn = min xa xb + 1; mx = max xa xb - 1; in [mn..mx]
    ys = let mn = min ya yb; mx = max ya yb; in [mn..mx]

import Data.List

data Circle = Circle Int Int Int

outsideCircles circles (x, y) = and $ map outside circles
  where outside (Circle a b r) = r*r < (a-x)*(a-x) + (b-y)*(b-y)

notCovered ((a, b), (c, d)) circles = length blankets
  where generals = nub $ concat [ [(x, b) | x <- [(min a c)..(max a c)]],
                                  [(x, d) | x <- [(min a c)..(max a c)]],
                                  [(a, y) | y <- [(min b d)..(max b d)]],
                                  [(c, y) | y <- [(min b d)..(max b d)]] ]
        blankets = filter (outsideCircles circles) generals

readInput :: IO (((Int, Int), (Int, Int)), [Circle])
readInput = do
  line <- getLine
  let nos = map (\x -> read x :: Int) (words line)
      [a, b, c, d] = nos
  line <- getLine
  let n = read line :: Int
  let getCircle = do
        line <- getLine
        let [a, b, r] = words line
            c = Circle (read a) (read b) (read r)
        return c
  circles <- sequence $ take n $ repeat getCircle
  return (((a, b), (c, d)), circles)

main = do
  (rect, circles) <- readInput
  let ans = notCovered rect circles
  putStrLn $ show ans

import Control.Monad

sqr x = x * x

check ps (x, y) =
  not $ or $ map (\[px, py, pr] -> pr * pr >= sqr (x - px) + sqr (y - py)) ps

solve xa ya xb yb ps = a + b + c + d
  where a = length $ filter (check ps) [(x, ya) | x <- [xa .. xb]]
        b = length $ filter (check ps) [(x, yb) | x <- [xa .. xb]]
        c = length $ filter (check ps) [(xa, y) | y <- [ya + 1 .. yb - 1]]
        d = length $ filter (check ps) [(xb, y) | y <- [ya + 1 .. yb - 1]]

main = do [xa, ya, xb, yb] <- fmap (map read.words) getLine
          n <- fmap read getLine
          ps <- replicateM n (fmap (map read.words) $ getLine)
          putStrLn $ show $ solve (min xa xb) (min ya yb) (max xa xb) (max ya yb) ps

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

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

parseInput = do
    p1 <- (,) <$> readInt <*> readInt
    p2 <- (,) <$> readInt <*> readInt
    n <- readInt
    circles <- replicateM n (Circle <$> readInt <*> readInt <*> readInt)
    return (p1, p2, circles)
  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'

data Circle = Circle Int Int Int

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

inCircle :: (Int, Int) -> Circle -> Bool
inCircle (x', y') (Circle x y r) = (x'-x)*(x'-x) + (y'-y)*(y'-y) <= r*r

range x y | x <= y    = tail [x..y]
          | otherwise = tail $ reverse [y..x]

solve ((x1, y1), (x2, y2), circles) = length $ filter (not.inAnyCircle) border
  where
    inAnyCircle pt = any (pt `inCircle`) circles

    border = [(x, y1) | x <- range x1 x2] ++
             [(x2, y) | y <- range y1 y2] ++
             [(x, y2) | x <- range x2 x1] ++
             [(x1, y) | y <- range y2 y1]

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

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

import Control.Monad
import Data.List
main = do
  [xa,ya,xb,yb] <- liftM (map read . words) getLine
  let x1 = min xa xb
      x2 = max xa xb
      y1 = min ya yb
      y2 = max ya yb
      gs = [ (x,y1) | x <- [x1..x2] ] ++
           [ (x,y2) | x <- [x1..x2] ] ++
           [ (x1,y) | y <- [y1+1..y2-1] ] ++
           [ (x2,y) | y <- [y1+1..y2-1] ]
  n <- readLn
  rs <- replicateM n $ liftM (map read . words) getLine
  print $ length $ foldl' f gs rs
f gs = flip filter gs . outOfRange
outOfRange [xr,yr,r] (x,y) = (xr-x)^2 + (yr-y)^2 > r^2

import Data.List(sort)
import Control.Applicative

main = do [xa,ya,xb,yb] <- map read . words <$> getLine
          _ <- getLine
          xyrs <- map (map read . words) . lines <$> getContents
          print $ solve [xa,ya,xb,yb] xyrs

solve :: [Int] -> [[Int]] -> Int
solve [xa',ya',xb',yb'] xyrs = length $ filter (\ (x,y) -> all (f (x,y)) xyrs) xys
   where [xa,xb] = sort [xa',xb']
         [ya,yb] = sort [ya',yb']
         xys = [(x,y)|x<-[xa,xb],y<-[ya..yb]] ++ [(x,y)|x<-[(succ xa)..(pred xb)],y<-[ya,yb]]

f (x,y) [xi,yi,ri] = (x-xi)*(x-xi) + (y-yi)*(y-yi) > ri*ri

import Control.Monad
import Data.List

type Point = (Int, Int)
type Radiator = (Int, Int, Int)

check (x, y) (xc, yc, r) =
    let dx = x - xc
        dy = y - yc
    in dx * dx + dy * dy <= r * r

solve xa ya xb yb rads =
    let pts = [(xa, y) | y <- [ya..yb]]
           ++ [(xb, y) | y <- [ya..yb]]
           ++ [(x, ya) | x <- [xa+1..xb-1]]
           ++ [(x, yb) | x <- [xa+1..xb-1]]
    in length pts - (length . filter id $
        map (\pt -> any (check pt) rads) pts)

main = do
    [xa, ya, xb, yb] <- liftM (map read . words) getLine :: IO [Int]
    n <- liftM read getLine
    list <- replicateM n $ do
        [xc, yc, r] <- liftM (map read . words) getLine :: IO [Int]
        return (xc, yc, r)

    let [xa', xb'] = sort [xa, xb]
        [ya', yb'] = sort [ya, yb]
    let ans = solve xa' ya' xb' yb' list

    putStrLn $ show ans

m a b=(min a b,max a b)
s([x,y,v,w]:[n]:t)=filter b[(i,j)|i<-[l..r],j<-[u,d]]++[(i,j)|j<-[u+1..d-1],i<-[l,r]]where(l,r)=m x v;(u,d)=m y w;b(x,y)=all(\[i,j,r]->(i-x)^2+(j-y)^2>r^2)t
main=interact$show.length.s.map(map read.words).lines


module Main where

import Data.List

main :: IO ()
main = do
    n <- readLn
    a <- sort <$> map read <$> words <$> getLine
    print $ f a n

f :: [Integer] -> Int -> Integer
f a n = (val . fst $ parts) + (val . snd $ parts)
    where sqr = \x -> x * x
          parts = splitAt (div n 2) a
          val = sqr . sum

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

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

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

-- import Debug.Trace
import Text.Printf

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

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

modifyArray a i f = writeArray a i =<< f <$> readArray a i

main = do
	n <- readInt
	as <- reverse . sort <$> readIntegers
	let
		hor = sum $ take ( ( n + 1 ) `div` 2 ) as
		ver = sum $ drop ( ( n + 1 ) `div` 2 ) as
	print $ hor ^ 2 + ver ^ 2

import Data.List

main :: IO ()
main = do
    n <- readLn
    as <- (map read.words) <$> getLine
    print $ solve n as

solve :: Int -> [Integer] -> Integer
solve n as = sum a^(2) + sum b^(2)
  where
    (a,b) =splitAt (n `div` 2) $ sort as

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE MultiWayIf        #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE ViewPatterns      #-}
#ifndef DEBUG
{-# LANGUAGE Safe              #-}
#endif

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.State.Strict
import qualified Data.Array                 as A
import qualified Data.Array.Unboxed         as UA
import qualified Data.Array.ST.Safe         as MA
import           Data.Bool
import qualified Data.ByteString.Builder    as B
import qualified Data.ByteString.Char8      as C
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict         as IM
import qualified Data.IntSet                as IS
import qualified Data.List                  as L
import qualified Data.List.NonEmpty         as NL
import           Data.Monoid
import qualified Data.Map.Strict            as M
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup
import qualified Data.Set                   as S
import           Data.Tuple
import           Foreign
import qualified System.IO                  as IO
#ifdef DEBUG
import           Debug.Trace
#endif

main :: IO ()
main = do
  !n <- readLn
  xs <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine
  print $ solve n xs

solve :: Int -> [Int] -> Integer
solve n xs = sum[fromIntegral y|y<-ys]^2 + sum[fromIntegral z|z<-zs]^2
  where
    (ys, zs) = splitAt (div n 2) $ L.sort xs

import Data.List

main :: IO ()
main = do
    n <- readLn
    as <- (map read.words) <$> getLine
    print $ solve n as

solve :: Int -> [Int] -> Int
solve n as = sum a^(2::Int) + sum b^(2::Int)
  where
    (a,b) =splitAt (n `div` 2) $ sort as


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

import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.Array as A
import Data.Array.ST(runSTArray)
import Data.Array.MArray
import Debug.Trace

type Map2D a = A.Array (Int,Int) a

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
near (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]

main = do
    [r,c] <- map readInt . B.words <$> B.getLine
    l <- B.lines <$> B.getContents
    let bb = ((0,0),(r-1,c-1))
    let mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]
    print $ solve r c mymap

solve r c mymap = foldl' (+) 0 $ do
    (p,c) <- breeders
    guard $ isJust (cost A.! p) && fromJust (cost A.! p) <= mycost
    return (digitToInt c)
    where
    start = head $ findPos (=='S') mymap
    exit  = head $ findPos (=='E') mymap
    mycost = fromJust (cost A.! fst start)
    breeders = findPos (\c -> '0' < c && c <= '9') mymap
    cost  = calcDistance (fst exit) mymap

findPos :: (a -> Bool) -> Map2D a -> [((Int,Int),a)]
findPos prop l = [ (p,c) | (p,c) <- A.assocs l, prop c ]

calcDistance :: (Int,Int) -> Map2D Char -> Map2D (Maybe Int)
calcDistance st mymap = runSTArray $ do
    cost <- newArray bb Nothing
    go cost
    return cost
    where
    bb  = A.bounds mymap
    canEnter p = inRange bb p && mymap A.! p /= 'T'
    go cost = loop [st] [] 0
        where
        loop [] [] c = return ()
        loop [] l  c = loop l [] (c+1)
        loop (p:ps) l c | not (canEnter p) = loop ps l c
                        | otherwise = do
            v <- readArray cost p
            case v of
                Nothing -> do
                    writeArray cost p (Just c)
                    loop ps ((filter canEnter $ near p)++l) c
                Just _ -> loop ps l c

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# OPTIONS_GHC -O3 #-}

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
-- import Data.Array
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

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

main = do
  [r, c] <- map read . words <$> getLine
  a <- replicateM r getLine

  let
    a' = listArray ((1, 1), (r, c)) $ concat a :: UArray (Int, Int) Char

    end = head [(x, y) | x <- [1..r], y <- [1..c], a'!(x, y) == 'E']

  let
    ds = runSTUArray $ do
      ds :: STUArray s (Int, Int) Int <- newArray ((1, 1), (r, c)) (-1)
      writeArray ds end 0

      let
        loop q =
          case Seq.viewl q of
            Seq.EmptyL -> return ()
            (p Seq.:< q') -> do
              d <- readArray ds p
              let ps = filter (\(x, y) -> 1 <= x && x <= r && 1 <= y && y <= c && a'!(x, y) /= 'T') [(x+1, y), (x-1, y), (x, y+1), (x, y-1)] where (x, y) = p

              ps' <- filterM (\p -> (== (-1)) <$> readArray ds p) ps
              forM_ ps' $ \p -> writeArray ds p (d+1)

              loop $ foldl (Seq.|>) q' ps'

      loop $ Seq.singleton end
      return ds

  let
    start = head [(x, y) | x <- [1..r], y <- [1..c], a'!(x, y) == 'S']
    d0 = ds!start
    mikes = [p | x <- [1..r], y <- [1..c], let p = (x, y), '1' <= (a'!p), (a'!p) <= '9']

  print $ sum $ map (\p -> fromEnum (a'!p) - fromEnum '0') $ filter (\p -> ds!p /= -1 && ds!p <= d0) mikes

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

import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.Array as A
import Data.Array.ST(runSTArray)
import Data.Array.MArray
import Debug.Trace

type Map2D a = A.Array (Int,Int) a

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
near (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]

main = do
    [r,c] <- map readInt . B.words <$> B.getLine
    l <- B.lines <$> B.getContents
    let bb = ((0,0),(r-1,c-1))
    let mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]
    print $ solve r c mymap

solve r c mymap = foldl' (+) 0 $ do
    (p,c) <- breeders
    guard $ isJust (cost A.! p) && fromJust (cost A.! p) <= mycost
    return (digitToInt c)
    where
    start = head $ findPos (=='S') mymap
    exit  = head $ findPos (=='E') mymap
    mycost = fromJust (cost A.! fst start)
    breeders = findPos (\c -> '0' < c && c <= '9') mymap
    cost  = calcDistance (fst exit) mymap

findPos :: (a -> Bool) -> Map2D a -> [((Int,Int),a)]
findPos prop l = [ (p,c) | (p,c) <- A.assocs l, prop c ]

calcDistance :: (Int,Int) -> Map2D Char -> Map2D (Maybe Int)
calcDistance st mymap = runSTArray $ do
    cost <- newArray bb Nothing
    go cost
    return cost
    where
    bb  = A.bounds mymap
    canEnter p = inRange bb p && mymap A.! p /= 'T'
    go cost = loop [(st,0)] []
        where
        loop [] [] = return ()
        loop [] l  = loop l []
        loop ((p,c):ps) l | not (canEnter p) = loop ps l
                          | otherwise = do
            v <- readArray cost p
            case v of
                Nothing -> do
                    writeArray cost p (Just c)
                    loop ps (map (\p -> (p,c+1)) (near p)++l)
                Just _ -> loop ps l

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

import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.Array as A
import Data.Array.ST(runSTArray)
import Data.Array.MArray

type Map2D a = A.Array (Int,Int) a

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
near (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]

main = do
    [r,c] <- map readInt . B.words <$> B.getLine
    l <- B.lines <$> B.getContents
    let bb = ((0,0),(r-1,c-1))
    let mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]
    print $ solve r c mymap

solve r c mymap = foldl' (+) 0 $ do
    (p,c) <- breeders
    guard $ isJust (cost A.! p) && fromJust (cost A.! p) <= mycost
    return (digitToInt c)
    where
    start = head $ findPos (=='S') mymap
    exit  = head $ findPos (=='E') mymap
    mycost = fromJust (cost A.! fst start)
    breeders = findPos (\c -> '0' < c && c <= '9') mymap
    cost  = calcDistance (fst exit) mymap

findPos :: (a -> Bool) -> Map2D a -> [((Int,Int),a)]
findPos prop l = [ (p,c) | (p,c) <- A.assocs l, prop c ]

calcDistance :: (Int,Int) -> Map2D Char -> Map2D (Maybe Int)
calcDistance st mymap = runSTArray $ newArray bb Nothing >>= go
    where
    bb  = A.bounds mymap
    canEnter p = inRange bb p && mymap A.! p /= 'T'
    go cost = loop [st] [] 0
        where
        loop [] [] c = return cost
        loop [] l  c = loop l [] (c+1)
        loop (p:ps) l c = do
            b <- isJust <$> readArray cost p
            when (not b) $ writeArray cost p (Just c)
            let l' = if b then l else (filter canEnter $ near p)++l
            loop ps l' c

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

import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.Array.Unboxed as A
import Data.Array.ST(runSTUArray)
import Data.Array.MArray

type Map2D a = A.UArray (Int,Int) a

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
near (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]

main = do
    [r,c] <- map readInt . B.words <$> B.getLine
    l <- B.lines <$> B.getContents
    let bb = ((0,0),(r-1,c-1))
    let mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]
    print $ solve r c mymap

solve :: Int -> Int -> Map2D Char -> Int
solve r c mymap = foldl' (+) 0 $ do
    (p,c) <- breeders
    guard $ (>=0) (cost A.! p) && (cost A.! p) <= mycost
    return (digitToInt c)
    where
    start = head $ findPos (=='S') mymap
    exit  = head $ findPos (=='E') mymap
    mycost = cost A.! fst start
    breeders = findPos (\c -> '0' < c && c <= '9') mymap
    cost  = calcDistance (fst exit) mymap

findPos :: (Char -> Bool) -> Map2D Char -> [((Int,Int),Char)]
findPos prop l = [ (p,c) | (p,c) <- A.assocs l, prop c ]

calcDistance :: (Int,Int) -> Map2D Char -> Map2D Int
calcDistance st mymap = runSTUArray $ newArray bb (-1) >>= go
    where
    bb  = A.bounds mymap
    canEnter p = inRange bb p && mymap A.! p /= 'T'
    go cost = loop [st] [] 0
        where
        loop [] [] c = return cost
        loop [] l  c = loop l [] (c+1)
        loop (p:ps) l c = do
            b <- (>=0) <$> readArray cost p
            when (not b) $ writeArray cost p (c)
            let l' = if b then l else (filter canEnter $ near p)++l
            loop ps l' c

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# OPTIONS_GHC -O3 #-}

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
-- import Data.Array
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

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

main = do
  [r, c] <- map read . words <$> getLine
  a <- replicateM r getLine

  let
    a' = listArray ((1, 1), (r, c)) $ concat a :: UArray (Int, Int) Char

    end = head [(x, y) | x <- [1..r], y <- [1..c], a'!(x, y) == 'E']

  let
    ds = runSTUArray $ do
      ds :: STUArray s (Int, Int) Int <- newArray ((1, 1), (r, c)) (-1)
      writeArray ds end 0

      let
        loop q =
          case Seq.viewl q of
            Seq.EmptyL -> return ()
            (p Seq.:< q') -> do
              d <- readArray ds p
              let ps = filter (\(x, y) -> 1 <= x && x <= r && 1 <= y && y <= c && a'!(x, y) /= 'T') [(x+1, y), (x-1, y), (x, y+1), (x, y-1)] where (x, y) = p

              ps' <- filterM (\p -> (== (-1)) <$> readArray ds p) ps
              forM_ ps' $ \p -> writeArray ds p (d+1)

              loop $ foldl (Seq.|>) q' ps'

      loop $ Seq.singleton end
      return ds

  let
    start = head [(x, y) | x <- [1..r], y <- [1..c], a'!(x, y) == 'S']
    d0 = ds!start
    mikes = [p | x <- [1..r], y <- [1..c], let p = (x, y), '1' <= (a'!p), (a'!p) <= '9']

  print $ sum $ map (\p -> fromEnum (a'!p) - fromEnum '0') $ filter (\p -> ds!p <= d0) mikes

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

import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.Array as A
import Data.Array.ST(runSTArray)
import Data.Array.MArray

readInt = B.readInt >>> fmap fst >>> fromMaybe 0

main = do
    [r,c] <- map readInt . B.words <$> B.getLine
    l <- B.lines <$> B.getContents
    print $ solve r c l

solve r c l = foldl' (+) 0 $ do
    (p,c) <- breeders
    guard $ isJust (cost A.! p) && fromJust (cost A.! p) <= mycost
    return (digitToInt c)
    where
    start = head $ findPos (=='S') l
    exit  = head $ findPos (=='E') l
    mycost = fromJust (cost A.! fst start)
    breeders = findPos (\c -> '0' < c && c <= '9') l
    cost  = calcDistance (fst exit) l

calcDistance :: (Int,Int) -> [B.ByteString] -> A.Array (Int,Int) (Maybe Int)
calcDistance st l = runSTArray $ do
    cost <- newArray bb Nothing
    go cost
    return cost
    where
    r   = length l
    c   = B.length (head l)
    bb  = ((0,0),(r-1,c-1))
    mymap = A.listArray bb $ [ B.index s i | s <- l , i <- [0..c-1]]
    canEnter p = inRange bb p && mymap A.! p /= 'T'
    go cost = loop [(st,0)] []
        where
        loop [] [] = return ()
        loop [] l  = loop l []
        loop ((p,c):ps) l | not (canEnter p) = loop ps l
                          | otherwise = do
            v <- readArray cost p
            case v of
                Nothing -> do
                    writeArray cost p (Just c)
                    loop ps (map (\p -> (p,c+1)) (near p)++l)
                Just _ -> loop ps l

near (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]

findPos :: (Char -> Bool) -> [B.ByteString] -> [((Int,Int),Char)]
findPos p l = do
    (s,i) <- zip l [0..]
    j     <- [0..B.length s-1]
    let c = B.index s j
    guard (p c)
    return ((i,j),c)