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)


{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

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

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

main = do
  n <- readLn
  ss <- replicateM n (B.init <$> B.getLine)

  let
    rs = process HashMap.empty ss
      where
        process _ [] = []
        process m (s:ss) =
          case s `HashMap.lookup` m of
            Nothing -> (B.pack "OK"):(process (HashMap.insert s 1 m) ss)
            Just k -> (B.append s (B.pack $ show k)):(process (HashMap.adjust (+1) s m) ss)

  B.putStr $ B.unlines rs

import Data.List
import qualified Data.Map as M

parse = tail . lines
present = unlines
solve = snd . mapAccumL insertName M.empty

insertName :: (M.Map String Int) -> String -> (M.Map String Int, String)
insertName olds new =
  let
    name = case M.findWithDefault 0 new olds of
      0 -> "OK"
      x -> new ++ (show x)
  in
  (M.insertWith (+) new 1 olds, name)

main = interact $ present . solve . parse

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
import Data.List
import qualified Data.Map as M

parse = tail . lines
present = unlines
solve !l = snd $ mapAccumL insertName M.empty l

insertName :: (M.Map String Int) -> String -> (M.Map String Int, String)
insertName olds new =
  let
    name = case M.findWithDefault 0 new olds of
      0 -> "OK"
      x -> new ++ (show x)
  in
  (M.insertWith (+) new 1 olds, name)

main = interact $ present . solve . parse

{-# OPTIONS_GHC -rtsopts -O2 #-}
import Data.List
import qualified Data.Map as M

parse = tail . lines
present = unlines
solve l = snd $ mapAccumL insertName M.empty l

insertName :: (M.Map String Int) -> String -> (M.Map String Int, String)
insertName olds new =
  let
    name = case M.findWithDefault 0 new olds of
      0 -> "OK"
      x -> new ++ (show x)
  in
  (M.insertWith (+) new 1 olds, name)

main = interact $ present . solve . parse

import qualified Data.Map as M
main = interact $ unlines.f.tail.words

f x = g (M.empty) x

g :: (M.Map String Int) -> [String] -> [String]
g a [] = []
g a b =
    let key = M.findWithDefault 0 (head b) a in
    if key == 0
    then "OK": g (M.insert (head b) 1 a) (tail b)
    else ((head b) ++ show key) : g (M.insert (head b) (key + 1) a) (tail b)

import Data.List
import Data.Map (Map)
import qualified Data.Map as Map

handle :: Map String Int -> String -> (Map String Int, String)
handle ac ar = (Map.insertWith (+) ar 1 ac, maybe "OK" (\x -> ar ++ (show x)) $ Map.lookup ar ac)

run :: String -> String
run xs = unlines $ snd $ mapAccumL (handle) Map.empty (tail $ lines xs)

main = interact run

import Data.List
import qualified Data.Map as M

solve acc x = (M.insertWith (+) x 1 acc, oStr)
  where oStr = if x `M.member` acc then x ++ show (acc M.! x) else "OK"

main = interact $ unlines . snd . mapAccumL solve M.empty . tail . words

import Data.List
import qualified Data.Map as M

solve acc x = (M.insertWith (+) x 1 acc, maybe "OK" ((x ++) . show) $ M.lookup x acc)

main = interact $ unlines . snd . mapAccumL solve M.empty . tail . words

{-# LANGUAGE ScopedTypeVariables,TupleSections #-}
import Control.Monad
import Data.Map
data State s a = State {runState :: s->(a,s)}
instance Monad (State s) where
	return = State . (,)
	(State f1) >>= f2 = State $ uncurry (runState . f2) . f1
	(State f1) >> (State f2) = State $ f2 .snd . f1

repeatM a = mapM (const a) (repeat 1)
repeatMn a n = mapM (const a) [1..n]
readm::(Read a) => State String a
readm = State (head . reads)
readchar = State (\s->(head s,tail s))
readall = State (,"")

runRead x s = fst $ runState x s

solve::Map String Int -> [String] -> [String]
solve _ [] = []
solve m (s:ss) = s1 : solve m1 ss where
	(s1,m1) = case (Data.Map.lookup s m) of
		Nothing -> ("OK",insert s 1 m)
		Just x -> (s++show x,insert s (x+1) m)
main = reader >>= writer . solver
reader = getContents
writer = putStr
solver = runRead $ do
	n <- readm
	l <- liftM lines readall
	return (unlines . solve empty . take n  . tail $ l)

module Main where

import Control.Monad
import Data.Char
import qualified Data.HashTable as Hash

main = do
    idHash <- Hash.new (==) Hash.hashString :: IO (Hash.HashTable [Char] Int)

    n <- read `liftM` getLine
    replicateM_ n $ do
        id <- getLine
        maybeCount <- Hash.lookup idHash id
        case maybeCount of
            Just n -> do
                Hash.update idHash id (n+1)
                putStrLn $ id ++ show n
            _ -> do
                Hash.insert idHash id 1
                putStrLn "OK"

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

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

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

main = do
  n <- readLn
  ss <- replicateM n (B.init <$> B.getLine)

  let
    rs = snd $ mapAccumL f HashMap.empty ss
      where
        f m s =
          case s `HashMap.lookup` m of
            Nothing -> (HashMap.insert s 1 m, B.pack "OK")
            Just k -> (HashMap.adjust (+1) s m, B.append s (B.pack $ show k))

  B.putStr $ B.unlines rs

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

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

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

main = do
  n <- readLn
  ss <- replicateM n getLine

  let
    rs = process HashMap.empty ss
      where
        process _ [] = []
        process !m (s:ss) =
          case s `HashMap.lookup` m of
            Nothing -> "OK":(process (HashMap.insert s 1 m) ss)
            Just k -> (s ++ show k):(process (HashMap.adjust (+1) s m) ss)

  putStr $ unlines rs

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

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

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

main = do
  n <- readLn
  ss <- replicateM n (B.init <$> B.getLine)

  let
    rs = process Map.empty ss
      where
        process _ [] = []
        process m (s:ss) =
          case s `Map.lookup` m of
            Nothing -> (B.pack "OK"):(process (Map.insert s 1 m) ss)
            Just k -> (B.append s (B.pack $ show k)):(process (Map.adjust (+1) s m) ss)

  B.putStr $ B.unlines rs

import qualified Data.Map.Strict as M
import Control.Monad (replicateM,foldM_)

(-->) = flip fmap

main = do
  n <- getLine --> read :: IO Int
  let doit m _ = do name <- getLine
                    case M.lookup name m of
                     Nothing -> do putStrLn "OK"
                                   return $ M.insert name 1 m
                     Just n  -> do putStrLn $ name ++ show n
                                   return $ M.insert name (n+1) m
  foldM_ doit (M.empty :: M.Map String Int) [1..n]

import qualified Data.Map.Strict as M
import Control.Monad (replicateM,foldM_)
import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char

(-->) = flip fmap

main = do
  n <- getLine --> read :: IO Int
  let doit m _ = do name' <- BS.getLine
                    let name = BS.takeWhile (not . isSpace) name'
                    case M.lookup name m of
                     Nothing -> do putStrLn "OK"
                                   return $ M.insert name 1 m
                     Just n  -> do BS.putStrLn $ name `BS.append` (BS.pack $ show n)
                                   return $ M.insert name (n+1) m
  foldM_ doit (M.empty :: M.Map ByteString Int) [1..n]

module Main (main) where

import qualified Data.HashTable as H

main = do
	map <- H.new (==) H.hashString
	instr <- getLine
	let n = read instr :: Int
	inloop n map

inloop 0 _ = do return ()
inloop n map = do
	key <- getLine
	v <- H.lookup map key
	let x = maybe 0 id v
	if x == 0 then do putStrLn "OK" else do putStrLn (key ++ show x)
	H.insert map key (x + 1)
	inloop (n - 1) map

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as M
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  readLn >>= \n ->  (mapM_ putStrLn).solve =<< (forM [1..n] $ \i ->  getLine>>= \j -> return (j))
--solve :: [String]-> [String]
solve (x:xs) = slv1 (x:xs) M.empty
slv1 [] ys =[]
slv1 (x:xs) ms =  let (z1, z2) = M.insertLookupWithKey (\ k n o -> 1+o) x 0 ms in if z1==Nothing then "OK":slv1 xs z2 else (x++show (z2 M.! x)):slv1 xs z2

import Data.Map (Map, empty, insert, findWithDefault)

solve :: [String] -> [String]
solve  =  tail . map fst . scanl f ("", empty)
  where
    f :: (String, Map String Int) -> String -> (String, Map String Int)
    f (_, map) name  =  (name', map')
      where
        n  =  findWithDefault 0 name map
        name'  =  if n == 0 then "OK" else name ++ (show n)
        map'  =  insert name (n+1) map

main :: IO ()
main  =  do
    n  <-  readLn
    names  <-  mapM (const getLine) [1..n]
    mapM_ putStrLn $ solve names

-- Codeforces 4C

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

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    solve Map.empty n

-- Note:
--  1. don't store the result, input a line, then compute, then print result.
--  2. use Map.insertWith to combine the old value and new value.

solve :: Map.Map String Int -> Int -> IO ()
solve _ 0 = return ()
solve db n = do
    req <- getLine
    putStrLn $ case Map.lookup req db of
        Just c -> req ++ show c
        Nothing -> "OK"
    solve (Map.insertWith (+) req 1 db) (n-1)

import qualified Data.Map as M
import Data.Map (Map)
import Data.Maybe

updateMap :: Map String Int -> String -> Map String Int
updateMap dataset str  = M.insertWith (+) str 1 dataset

loop :: Int -> Map String Int -> IO (Map String Int)
loop 0 dataset = return dataset
loop n dataset = do
    str <- getLine
    let a = M.lookup str dataset
    if isNothing a then
            putStrLn "OK"
        else
            putStrLn (str ++ show (fromJust a))
    let newSet = updateMap dataset str
    loop (n - 1) newSet

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    dataset <- loop n M.empty
    return ()

import qualified Data.Map as M
import Data.Map (Map)
import Data.Maybe

updateMap :: Map String Int -> String -> Map String Int
updateMap dataset str = M.insertWith (+) str 1 dataset
    where
        updater 0 _ = 1
        updater value _ = value + 1

loop :: Int -> Map String Int -> IO (Map String Int)
loop 0 dataset = return dataset
loop n dataset = do
    str <- getLine
    let a = M.lookup str dataset
    if isNothing a then
            putStrLn "OK"
        else

            putStrLn (str ++ show (fromJust a))
    let newSet = updateMap dataset str
    --print $ output
    loop (n - 1) newSet

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    dataset <- loop n M.empty
    return ()

import qualified Data.Map as M
import Data.Map (Map)
import Data.Maybe

updateMap :: Map String Int -> String -> Map String Int
updateMap dataset str = M.insertWith updater str 1 dataset
    where
        updater _ 0 = 1
        updater _ value = value + 1

loop :: Int -> Map String Int -> IO (Map String Int)
loop 0 dataset = return dataset
loop n dataset = do
    str <- getLine
    let a = M.lookup str dataset
    if isNothing a then
            putStrLn "OK"
        else
            putStrLn (str ++ show (fromJust a))
    let newSet = updateMap dataset str
    loop (n - 1) newSet

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    dataset <- loop n M.empty
    return ()

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

process::[String]->M.Map String Int->IO ()
process [] _ = putStrLn ""
process (q:qs) d | M.lookup q d== Nothing = do
                                                  putStrLn "OK"
                                                  process qs (M.insert q 1 d)
                     | otherwise = do
                                      let x = fromJust $ M.lookup q d
                                      putStrLn $ q++ (show x)
                                      process qs (M.insert q (x+1) d)

main=do
      getLine
      q<- lines<$>  getContents
      process  q  M.empty

import qualified Data.Map as M
import Data.List
main=getContents>>=mapM_ putStrLn.snd.mapAccumL(\m x->(M.insertWith(+)x(1::Integer)m,maybe"OK"((x++).show)(M.lookup x m)))M.empty.tail.lines

import qualified Data.Map as M
import Data.List
main=interact$unlines.snd.mapAccumL(\m x->(M.insertWith(+)x(1::Integer)m,maybe"OK"((x++).show)(M.lookup x m)))M.empty.tail.lines

import qualified Data.Map as M
import Data.List (mapAccumL)

main :: IO ()
main = getContents >>= mapM_ putStrLn . solve . tail . lines

solve :: [String] -> [String]
solve = snd . mapAccumL f M.empty
  where f m x = (M.insertWith (+) x (1 :: Integer) m, maybe "OK" ((x++) . show) (M.lookup x m))

import qualified Data.Map as M
import Control.Monad
main = do
  n <- readLn
  loop n M.empty
loop 0 _ = return ()
loop n m = do
  name <- getLine
  putStrLn $ case M.lookup name m of
               Just c -> name ++ show c
               Nothing -> "OK"
  loop (n-1) (M.insertWith (+) name 1 m)

import qualified Data.Map as M
import Control.Monad

type Names = M.Map String Int

solve :: Names -> a -> IO Names
solve m _ = do
    name <- getLine
    case lookup' name m of
        0 -> do
            putStrLn "OK"
            return $ M.insert name 1 m
        n -> do
            putStrLn $ name ++ show n
            return $ M.insert name (n + 1) m

lookup' :: String -> Names -> Int
lookup' k m = case M.lookup k m of
    Just v -> v
    Nothing -> 0

main :: IO ()
main = do
    n <- fmap read getLine
    foldM_ solve M.empty [1..n]

-- Vicfred
-- https://codeforces.com/problemset/problem/4/C

import Data.List
import qualified Data.Map as M

solve :: (Num a, Show a) => M.Map [Char] a -> [Char] -> (M.Map [Char] a, [Char])
solve acc x = (M.insertWith (+) x 1 acc, maybe "OK" ((x ++) . show) $ M.lookup x acc)

main :: IO ()
main = interact $ unlines . snd . mapAccumL solve M.empty . tail . words

import Data.List
import qualified Data.ByteString.Char8 as B
import Data.Map.Strict as M
import Control.Monad

f m s = case s `M.lookup` m of
          Just a -> (M.adjust (+1) s m, B.append s (B.pack $ show a))
          Nothing -> (M.insert s 1 m, B.pack "OK")
main = do
  n <- readLn
  rest <- replicateM n (B.init <$> B.getLine)
  let rs = snd $ mapAccumL f M.empty rest
  B.putStr $ B.unlines rs

import Data.List
import qualified Data.ByteString.Char8 as B
import Data.Map.Strict as M
import Control.Monad

f m s = case s `M.lookup` m of
          Just a -> (M.adjust (+1) s m, B.append s (B.pack $ show a))
          Nothing -> (M.insert s 1 m, B.pack "OK")
main = do
  n <- readLn
  rest <- replicateM n (head <$> B.words <$> B.getLine)
  let rs = snd $ mapAccumL f M.empty rest
  B.putStr $ B.unlines rs

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

main = readLn >>= foldM_ output Map.empty . enumFromTo 1
 where
  output mp _ = do
    s <- getLine
    putStrLn $ maybe "OK" ((s ++) . show) $ Map.lookup s mp
    return $ Map.insertWith' (fmap (+ 1) . const id) s 1 mp

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

data TrieLike a = Empty | Node {count :: Maybe Int, branches :: [(a, TrieLike a)]} deriving Show

modify' :: Ord a => a -> (TrieLike a -> TrieLike a) -> [(a, TrieLike a)] -> [(a, TrieLike a)]
modify' k f nodes = parse nodes
 where
  parse [] = [(k, f Empty)]
  parse xs@(x'@(k', t') : xs') =
    case compare k k' of
      LT -> (k , f Empty) : xs
      EQ -> (k', f t')    : xs'
      GT -> x'            : parse xs'

inc' :: TrieLike a -> TrieLike a
inc' Empty = Empty
inc' node  = node {count = Just . maybe 1 succ $ count node}

insert' :: Ord a => [a] -> TrieLike a -> TrieLike a
insert' xs       Empty = insert' xs $ Node Nothing []
insert' []       node  = inc' node
insert' (x : xs) node  = node {branches = modify' x (insert' xs) $ branches node}

lookup' :: Ord a => [a] -> TrieLike a -> Maybe (TrieLike a)
lookup' _  Empty       = Nothing
lookup' [] node        = Just node
lookup' (x : xs) node  = lookup x (branches node) >>= lookup' xs

next' :: Ord a => [a] -> TrieLike a -> Maybe Int
next' = fmap (join . fmap count) . lookup'

main = readLn >>= foldM_ output Empty . enumFromTo 1
 where
  output t _ = do
    s <- getLine
    putStrLn $ maybe "OK" ((s ++) . show) $ next' s t
    return $ insert' s t

import Data.HashTable as H
main = do
    hTable <- new (==) hashString
    n <- read `fmap` getLine
    mapM_ (\_ ->  do
        name <- getLine
        val <- H.lookup hTable name
        case val of
            Just count -> do
                putStr (name ++ show count ++ "\n")
                update hTable name (count + 1)
                return ()
            Nothing -> do
                putStr "OK\n"
                insert hTable name 1
        ) [1..n]
-- vim: set et sts=4:

import Control.Monad
import qualified Data.Map as M

main = do
     getLine
     foldM_ (\mapping name -> do
            let res = M.lookup name mapping
            if res == Nothing
               then putStrLn "OK" >> return (M.insert name 0 mapping)
               else let Just res' = res
                    in putStrLn (name++show (res'+1)) >> return (M.insert name (res'+1) mapping)
            ) M.empty =<< return . lines =<< getContents

module Main where

import Data.List (mapAccumL)
import qualified Data.Map.Strict as M

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

solve :: [String] -> [String]
solve names = snd $ mapAccumL processName M.empty names

processName :: M.Map String Int -> String -> (M.Map String Int, String)
processName occ name = (M.insertWith (+) name 1 occ, maybe "OK" ((name ++) . show) (M.lookup name occ))

module Main where

import Data.List (mapAccumL)
import qualified Data.Map.Strict as M

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

solve :: [String] -> [String]
solve names = snd $ mapAccumL processName M.empty names

processName :: M.Map String Int -> String -> (M.Map String Int, String)
processName occ name = case M.lookup name occ of
  Nothing     -> (M.insert name 1 occ, "OK")
  Just count  -> (M.insert name (count + 1) occ, name ++ show count)

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Data.Map
import Data.HashTable
import Debug.Trace
import Data.List
import Data.Array
import Data.Char
import Data.Int
class Scan a where scan' :: String -> a
instance Scan Int where scan' = read
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' = read
instance Scan Double where scan' = read
instance Scan Integer where scan' = read
instance Scan String where scan' x = x
scan :: (Scan a) => IO a
scan = getLine>>=(return.scan')
scans :: (Scan a) => Int -> IO [a]
scans n = if n==0 then return [] else scan>>=(\x->scans (n-1)>>=return.(x:))

solve [] _ l = reverse l
solve (x:xs) mp l = let mp' = insertWith (+) x 1 mp in
                    case Data.Map.lookup x mp of
                      Nothing -> (solve$!) xs mp' ("OK":l)
                      Just n -> (solve$!) xs mp' ((x++(show n)):l)

main = do n <- scan :: IO Int
          l <- scans n :: IO [String]
          hash <- new (==) hashString
          sequence_ [do val <- Data.HashTable.lookup hash x;case val of {Nothing -> Data.HashTable.insert hash x 1>>putStrLn "OK";Just n -> Data.HashTable.update hash x (n+1)>>putStrLn (x++(show n))}|x<-l]

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Data.HashTable
class Scan a where scan' :: String -> a
instance Scan Int where scan' = read
instance Scan String where scan' x = x
scan :: (Scan a) => IO a
scan = getLine>>=(return.scan')
scans :: (Scan a) => Int -> IO [a]
scans n = if n==0 then return [] else scan>>=(\x->scans (n-1)>>=return.(x:))

main = do n <- scan :: IO Int
          l <- scans n :: IO [String]
          hash <- new (==) hashString
          sequence_ [do val <- Data.HashTable.lookup hash x;case val of {Nothing -> Data.HashTable.insert hash x 1>>putStrLn "OK";Just n -> Data.HashTable.update hash x (n+1)>>putStrLn (x++(show n))}|x<-l]

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

process [] _   = return ()
process (a:as) m   | M.findWithDefault (-10) a m ==(-10) = do
								putStrLn "OK"
								process as (M.insert a 0 m )
		   | otherwise = do
					let m1 = (M.insertWith (+) a 1 m)
					putStrLn (a++show (M.findWithDefault (-10) a m1 ))
					process as  m1

main=do
	getLine
	a<-lines <$> getContents ::IO [String]
        process a M.empty

import qualified Data.Map as Map
import Control.Monad

insertFun::a->b->Int->Int
insertFun _ _ old_value = old_value + 1

forDisplay::String->Maybe Int->String
forDisplay request res = case res of
			      Just n -> request ++ show n
			      Nothing -> "OK"

work database request = do
  let tmp = fst res
  putStrLn (forDisplay request tmp)
  return (snd res)
  where res = Map.insertLookupWithKey insertFun request 1 database

process database _ = do
  request <- getLine
  ret <- work database request
  return ret

main = do
  n <- getLine
  foldM_ process Map.empty [1..read n::Int]

import Data.List (mapAccumL)
import Data.Maybe
import qualified Data.Map.Lazy as M

data Trie a = Trie { value :: Int
                   , getTrie :: M.Map a (Trie a)
                   } deriving (Eq)

empty :: Trie a
empty = Trie (-1) M.empty

insert :: Ord a => [a] -> Trie a -> Trie a
insert [] (Trie e m)     = Trie (e+1) m
insert (x:xs) (Trie e m) = Trie e (M.alter (Just . insert xs . fromMaybe empty) x m)

find :: Ord a => [a] -> Trie a -> Int
find [] (Trie e _)     = e
find (x:xs) (Trie _ m) = fromMaybe (-1) (find xs <$> M.lookup x m)

--process :: [String] -> [String]
process xs = zipWith g xs $ snd $ mapAccumL f empty xs
    where
        f s l = (s', i)
            where
                s' = insert l s
                i = find l s'
        g x i = if i == 0
                    then "OK"
                    else x ++ show i

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap lines getContents
    putStrLn.unlines $ process xs

{-# LANGUAGE ScopedTypeVariables,TupleSections #-}
import Control.Monad
import Data.Map
data State s a = State {runState :: s->(a,s)}
instance Monad (State s) where
	return = State . (,)
	(State f1) >>= f2 = State $ uncurry (runState . f2) . f1
	(State f1) >> (State f2) = State $ f2 .snd . f1

repeatM a = mapM (const a) (repeat 1)
repeatMn a n = mapM (const a) [1..n]
readm::(Read a) => State String a
readm = State (head . reads)
readchar = State (\s->(head s,tail s))
readall = State (,"")

runRead x s = fst $ runState x s

solve::Map String Int -> [String] -> [String]
solve _ [] = []
solve m (s:ss) = s1 : solve m1 ss where
	(s1,m1) = case (Data.Map.lookup s m) of
		Nothing -> ("OK",insert s 1 m)
		Just x -> (s++show (x+1),insert s (x+1) m)
main = reader >>= writer . solver
reader = getContents
writer = putStr
solver = runRead $ do
	n <- readm
	l <- liftM lines readall
	return (unlines . solve empty . take n  . tail $ l)

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

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

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

main = do
  n <- readLn
  ss <- replicateM n B.getLine

  let
    rs = process HashMap.empty ss
      where
        process _ [] = []
        process !m (s:ss) =
          case s `HashMap.lookup` m of
            Nothing -> (B.pack "OK"):(process (HashMap.insert s 1 m) ss)
            Just k -> (B.append s (B.pack $ show k)):(process (HashMap.adjust (+1) s m) ss)

  B.putStr $ B.unlines rs

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

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

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

main = do
  n <- readLn
  ss <- replicateM n B.getLine

  let
    rs = process HashMap.empty ss
      where
        process _ [] = []
        process m (s:ss) =
          case s `HashMap.lookup` m of
            Nothing -> (B.pack "OK"):(process (HashMap.insert s 1 m) ss)
            Just k -> (B.append s (B.pack $ show k)):(process (HashMap.adjust (+1) s m) ss)

  putStr $ unlines $ map B.unpack rs

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

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

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

main = do
  n <- readLn
  ss <- replicateM n B.getLine

  let
    rs = process Map.empty ss
      where
        process _ [] = []
        process !m (s:ss) =
          case s `Map.lookup` m of
            Nothing -> (B.pack "OK"):(process (Map.insert s 1 m) ss)
            Just k -> (B.append s (B.pack $ show k)):(process (Map.adjust (+1) s m) ss)

  B.putStr $ B.unlines rs

import Data.List
import Data.Tree
import Data.Int
import Data.Word
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  getLine>>= \i -> C.interact $ C.unlines.solve. take (read i).C.lines
solve :: [C.ByteString]-> [C.ByteString]
solve xs =  map (\(a1,a2)->a1) $ sortBy (\ (a1,a2) (b1,b2) -> a2 `compare` b2) $ concat $ map slv2 $ slv1 xs
slv1::[C.ByteString]->[[(C.ByteString,Int)]]
slv1 xs= groupBy (\(a1,a2) (b1,b2)->a1==b1 ) $sortBy (\ (a1,a2) (b1,b2) -> a1 `compare` b1) $ zip xs [1..]
slv2 :: [(C.ByteString,Int)]->[(C.ByteString,Int)]
slv2 xs=zipWith (\ (a1,a2) b->if b==0 then (C.pack "OK",a2) else (C.append a1 (C.pack $ show b) ,a2) ) xs [0..]

import qualified Data.Map as M
import Data.Map (Map)

updateMap :: Map String Int -> String -> Map String Int
updateMap dataset str = M.insertWith (+) str 1 dataset
    where
        updater 0 _ = 1
        updater value _ = value + 1

loop :: Int -> Map String Int -> IO (Map String Int)
loop 0 dataset = return dataset
loop n dataset = do
    str <- getLine
    let newSet = updateMap dataset str
    loop (n - 1) newSet

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    dataset <- loop n M.empty
    print dataset

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

process::[String]->M.Map String Int->IO ()
process [] _ = putStrLn ""
process (q:qs) d | M.lookup q d== Nothing = do
                                                  putStrLn "Ok"
                                                  process qs (M.insert q 1 d)
                     | otherwise = do
                                      let x = fromJust $ M.lookup q d
                                      putStrLn $ q++ (show x)
                                      process qs (M.insert q (x+1) d)

main=do
      getLine
      q<- lines<$>  getContents
      process  q  M.empty

import Data.List
c1 = 27 ** 32
main = do
    n <- read `fmap` getLine
    l <- mapM (\i ->  (\s -> (s, i)) `fmap` getLine) [1..n]
    let l1 = concat $ map addNumb $ groupBy (\(a, _) (b, _) -> a == b) $ sort l where
            addNumb [(s, i)] = [("OK", i)]
            addNumb ((s, i):ss) = let
                a = foldl' (\(ss', n') (st, nline) ->
                    ((st++show n', nline):ss', n+1)) ([("OK", i)], 1) ss in fst a
    mapM_ (\s -> putStr (fst s ++ "\n")) $ sortBy (\(_, a) (_, b) -> a `compare` b) l1

import Control.Applicative
import Control.Monad
import qualified Data.Map.Strict as M
import qualified Data.ByteString.Char8 as C

process::[C.ByteString]->M.Map C.ByteString Int->IO ()
process [] _   = return ()
process (a:as) m   | M.findWithDefault (-10) a m ==(-10) = do
								putStrLn "OK"
								process as (M.insert a 0 m )
		   | otherwise = do
					let m1 = (M.insertWith (+) a 1 m)
					putStrLn $ (show a) ++ (show (M.findWithDefault (-10) a m1 ))
					process as  m1

main=do
	getLine
	a<-C.lines <$> C.getContents
        process a M.empty

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

process [] _ s = mapM_ putStrLn $ reverse s
process (a:as) m s | M.findWithDefault (-10) a m ==(-10) = process as (M.insert a 0 m )  ("Ok" : s)
		   | otherwise = process as  m1 ((a++show (M.findWithDefault (-10) a m1 )):s)
		where m1 = (M.insertWith (+) a 1 m)

main=do
	getLine
	a<-lines <$> getContents ::IO [String]
        process a M.empty []


{-# OPTIONS_GHC -O2 -optc-O2 #-}
module Main where

import Control.Monad (liftM, replicateM)
import Data.List (delete)

type Bottle = (Int, Int)

readInt :: String -> Int
readInt = read

cantBeOpened :: Bottle -> [Bottle] -> Bool
cantBeOpened b bs = null [x | x <- bs, snd x == t]
  where t = fst b

main = do
  numBottles <- liftM readInt getLine
  bottles <- replicateM numBottles $ do
    [a, b] <- liftM (map readInt . words) getLine
    return (a, b)
  let result = zipWith cantBeOpened bottles $ map (`delete` bottles) bottles
  print . length $ filter id result

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

solve con = filter (\[x,y]->x/=0) (res con [])
res [] acc = acc
res ([x,y]:xs) acc = res (sch (x,y) xs) ([x,y]:(sch (x,y) acc))
sch _ [] = []
sch (a,b) ([x,y]:xs)
    |b==x           = [0,y]:sch (a,b) xs
    |otherwise      = [x,y]:sch (a,b) xs

import Control.Monad (liftM)
import Data.List (delete)
import Prelude hiding (reads)

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

readPair :: Read a => IO (a, a)
readPair  =  do
    [x, y]  <-  reads
    return (x, y)

solve :: [(Int, Int)] -> Int
solve xs  =  length $ filter notOpen xs
  where
    notOpen x  =  notElem (fst x) $ map snd $ delete x xs

main :: IO ()
main  =  do
    n  <-  readLn
    xs  <-  sequence $ replicate n readPair
    print $ solve xs

import Control.Applicative
import Data.Array

main = do
    n <- read <$> getLine :: IO Int
    aa <- sequence $ take n $ repeat $ do
        s <- words <$> getLine
        return (read (s!!0), read (s!!1)) :: IO (Int, Int)
    let a = listArray (1, n) aa
    let goodL = filter (\i -> any (\j -> i /= j && fst (a!i) == snd (a!j)) [1..n]) [1..n]
    print $ n - length goodL

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

solve con = filter (\[x,y]->x/=0) (res con con)
res [] con = con
res ([x,y]:xs) con = res xs (sch (x,y) con)
sch _ [] = []
sch (a,b) ([x,y]:xs)
    |b==x&&a/=x     = [0,y]:sch (a,b) xs
    |otherwise      = [x,y]:sch (a,b) xs


-- https://codeforces.com/contest/1679/problem/D
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NumericUnderscores #-}

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.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.Maybe (fromJust, fromMaybe, isJust)

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
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 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 -}

stringValue :: B8.ByteString -> Int
stringValue str = sum . map (\c -> ord c - ord 'a' + 1) $ B8.unpack str

solve :: B8.ByteString -> (String, Int)
solve str
    | even $ B8.length str = valueToAnswer strValue
    | otherwise = valueToAnswer $ max (tailStrValue - headStrValue) (tailEndStrValue - headEndStrValue)
    where
        strValue = stringValue str

        tailStrValue = stringValue $ B8.drop 1 str
        headStrValue = stringValue $ B8.take 1 str

        tailEndStrValue = stringValue $ B8.take (B8.length str - 1) str
        headEndStrValue = stringValue $ B8.drop (B8.length str - 1) str

        valueToAnswer value
            | value > 0 = ("Alice", value)
            | value < 0 = ("Bob", - value)
            | otherwise = ("WTF", - value)

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        str <- B8.getLine <&> head . B8.words
        let (player, score) = solve str
        printf "%s %d\n" player score

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

solve :: IO ()
solve = do
    xs <- map ((+(-96)) . ord) . takeWhile (not . isSpace) . C.unpack <$> C.getLine
    let [sm, hx, lx] = ($xs) <$> [sum, head, last]
        diff
            | even (length xs) = sm
            | otherwise        = sm - 2 * min hx lx
    putStrLn $ (if diff > 0 then "Alice" else "Bob") ++ " " ++ show (abs diff)

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts


import Data.List
import Control.Applicative

main = do
	n <- read <$> getLine :: IO Int
	a <- take n <$> lines <$> getContents
	putStrLn $ mergeMatrix $ transpose a

mergeMatrix :: [[Char]] -> [Char]
mergeMatrix a
    | null a        = ""
    | otherwise     = (mergeString (head a)) : (mergeMatrix (tail a))

mergeString :: [Char] -> Char
mergeString s = finalize $ foldl mergeChar '.' s

mergeChar :: Char -> Char -> Char
mergeChar '.' '?' = '.'
mergeChar '.'   c = c
mergeChar '?'   c = '?'
mergeChar   c '?' = c
mergeChar   a   b = if a == b then a else '?'

finalize :: Char -> Char
finalize c
    | c == '.'      = 'x'
    | otherwise     = c

import Data.List
strToList = (map (read :: String -> Int)).words

f [] = ""
f (x:xs)  | length s > 1 = '?' : f xs
          | length s == 1 = s !! 0 : f xs
          | otherwise = 'a' : f xs
            where s = filter (/='?') (nub x)

main = do
    n <- readLn :: IO Int
    s <- getContents
    putStrLn $ f $ transpose $ lines s


{-# LANGUAGE BangPatterns, ViewPatterns #-}
import Data.List
import Data.Int
import Control.DeepSeq

main = do
    temp <- getLine
    let n = read temp :: Int
    input <- getContents
    putStrLn $ solve $ init $ take n $ lines input

mod_constant = 1000000007 :: Int64
a `modplus` b = (a + b) `rem` mod_constant

suffixSum = scanr1 modplus

dpStep (force -> !p) "s" = suffixSum p
dpStep (force -> !p) "f" = 0:p

solve :: [String] -> String
solve x = show $ foldl modplus 0 $ foldl dpStep [1] x

{-# LANGUAGE BangPatterns, ViewPatterns #-}
import Data.Int
import Data.List
import Control.DeepSeq
main = interact exec
exec = (\(n0:ss0) -> let n = read n0 :: Int; (s:ss) = map head ss0 in show $ f s (1:replicate (n - 1) 0) ss) . words

f 's' (force -> !ms) (s:ss) = f s (scanr1 (+%) ms) ss
f 'f' (force -> !ms) (s:ss) = f s (zipWith const (0:ms) ms) ss
f _   (force -> !ms) [] = foldl' (+%) 0 ms

mbase = 10^9 + 7 :: Int64
a +% b = (a + b) `rem` mbase

import Data.Int
import Data.List
import Control.DeepSeq
import qualified Data.ByteString.Char8 as B
main = B.interact exec
exec = (\(n0:ss0) -> let n = maybe undefined fst $ B.readInt n0; (s:ss) = map B.head ss0 in B.pack $ show $ f s (1:replicate (n - 1) 0) ss) . B.words

f 's' ms (s:ss) = f s (ms `deepseq` scanr1 (+%) ms) ss
f 'f' ms (s:ss) = f s (ms `deepseq` zipWith const (0:ms) ms) ss
f _   ms [] = foldl' (+%) 0 ms

mbase = 10^9 + 7 :: Int64
a +% b = (a + b) `rem` mbase

import Data.Foldable
import Data.Semigroup

main = interact $ show . solve . args . words
  where args :: [String] -> [Int]
        args (w:ws) = go (read w) 0 ws
          where go :: Int -> Int -> [String] -> [Int]
                go _ _ [] = []
                go n k (w:ws)
                  | n == 1    = []
                  | w == "f"  = go (n - 1) (k + 1) ws
                  | otherwise = (k + 1) : go (n - 1) 0 ws

solve :: [Int] -> Int
solve as = solve' as [1] 1
  where solve' :: [Int] -> [Int] -> Int -> Int
        solve' []     xs s = s
        solve' (a:as) xs s = solve' as xs' (foldl' modAdd 0 xs')
          where xs' = zipWith modSub (s : xs') (stimes a [0] ++ xs)

modConst :: Int
modConst = 1000000007

modSub :: Int -> Int -> Int
modSub a b = (a - b) `mod` modConst

modAdd :: Int -> Int -> Int
modAdd a b = (a + b) `mod` modConst

import Data.List

main = do
    temp <- getLine
    let n = read temp :: Int
    input <- getContents
    putStrLn $ solve $ init $ take n $ lines input

suffixSum p = map sum $ (init . tails) p

dpStep p "s" = map (\x -> x `mod` 1000000007) $ suffixSum p
dpStep p "f" = 0:p

solve :: [String] -> String
solve x = show $ sum $ foldl dpStep [1] x

import Data.List

main = do
    temp <- getLine
    let n = read temp :: Int
    input <- getContents
    putStrLn $ solve $ init $ take n $ lines input

addStep p "s" = reverse $ map sum $ (init . tails) p
addStep p "f" = 0:p

solve :: [String] -> String
solve x = show $ sum $ foldl addStep [1] x

import Data.List

main = do
    temp <- getLine
    let n = read temp :: Int
    input <- getContents
    putStrLn $ solve $ init $ take n $ lines input

suffixSum p = map sum $ (init . tails) p

addStep p "s" = suffixSum p
addStep p "f" = 0:p

solve :: [String] -> String
solve x = show $ sum $ foldl addStep [1] x

import Data.Semigroup

main = interact $ show . solve . args . words
  where args :: [String] -> [Int]
        args (w:ws) = go (read w) 0 ws
          where go :: Int -> Int -> [String] -> [Int]
                go _ _ [] = []
                go n k (w:ws)
                  | n == 1    = []
                  | w == "f"  = go (n - 1) (k + 1) ws
                  | otherwise = (k + 1) : go (n - 1) 0 ws

solve :: [Int] -> Int
solve as = solve' as [1] 1
  where solve' :: [Int] -> [Int] -> Int -> Int
        solve' []     xs s = s
        solve' (a:as) xs s = solve' as xs' (sum xs')
          where xs' = zipWith (-) (s : xs') (stimes a [0] ++ xs)


import Data.List
main=interact$show.sum.map((`div`4).(^2).(+(-1)).length).group.sort.map head.tail.lines

import Data.List

main = getContents >>= print . solve . tail . words

solve = sum . map ((\n -> let x = n `div` 2 in c x 2 + c (n - x) 2) . length) . group . sort . map head
    where c n 2 = n * (n - 1) `div` 2

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

half :: Int -> [Int]
half n = [a, n - a] where a = div n 2

handshakes :: Int -> Int
handshakes n = div (n * (n - 1)) 2

solve :: [String] -> Int
solve = sum
      . map handshakes
      . concat
      . map half
      . map length
      . group
      . sort
      . map head

main :: IO ()
main = do
    n <- readInt
    names <- replicateM n getLine
    print $ solve names

import Data.List

main = interact $ show . sum . map (sum . map (\x -> x * (x - 1) `div` 2) . (\x -> [x `div` 2, (x + 1) `div` 2]) . length) . group . sort . map head . tail . lines

import Data.List
import Data.Function
main = interact $ show . solve . sort . tail . lines
solve = sum . map (f . length) . groupBy ((==) `on` head)
f n = ps h + ps h' where h = n `div` 2; h' = h + n `mod` 2
ps n = n * (n-1) `div` 2

{-# 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
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readNInts = readInt >>= flip replicateM readInt

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

main = do
	n <- readInt
	ls <- map length . group . sort . map head <$> replicateM n getLine
	print $ solve ls

solve [] = 0
solve (l:ls) = f l1 + f l2 + solve ls
	where
		l1 = l `div` 2
		l2 = l - l1
		f x = x * ( x - 1 ) `div` 2

import Data.List
import Data.Function
import Data.Bifunctor

fac n = snd $ until ((<2). fst) (\(x,y) -> (x-1,y*x)) (toInteger n,1 :: Integer)
comb2 n = if n < 2 then 0 else (fac n ) `div` (fac $ n-2) `div` 2
clip n = if n < 0 then 0 else n
solve =  uncurry (+) .
         foldr (\(a,b) (x,y) -> (a+x,b+y)) (0,0) .
         map ((\x -> let y = x`div`2 in bimap comb2 comb2 (y, clip $ x-y)) . length) .
         groupBy ((==) `on` (!!0)) .
         sort
main = print =<< solve . tail . lines <$> getContents

import Data.List
import Data.Function
import Data.Bifunctor

fac n = snd $ until ((<2). fst) (\(x,y) -> (x-1,y*x)) (n,1)
comb2 n = if n < 2 then 0 else (fac n ) `div` (fac $ n-2) `div` 2
solve = uncurry (+)
        . foldr (\(a,b) (x,y) -> (a+x,b+y)) (0,0)
        . map ((\x -> let y = x`div`2 in bimap comb2 comb2 (y,x-y)) . length)
        . groupBy ((==) `on` (!!0))
        . sort
main = print =<< solve . tail . lines <$> getContents


import Data.Functor
import Data.List

getInts :: IO [Int]
getInts = map read <$> words <$> getContents

main = getInts >>= putStrLn . (\b -> if b then "Yes" else "No") . solve

solve :: [Int] -> Bool
solve (n:m:as) = (==g) . length . nub $ map f xs ++ map f ys where
    xn:as2 = as
    yn:as3 = drop xn as2
    xs = take xn as2
    ys = take yn as3
    g = gcd n m
    f = (flip mod) g

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Char
import Data.List
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  [n, m] <- fmap (map read . words) getLine
  xs <- fmap (tail . map read . words) getLine
  ys <- fmap (tail . map read . words) getLine

  let
    check = runST $ do
      as <- newArray (0, n-1) False :: ST s (STUArray s Int Bool)
      mapM_ (\x -> writeArray as x True) xs

      bs <- newArray (0, m-1) False :: ST s (STUArray s Int Bool)
      mapM_ (\x -> writeArray bs x True) ys

      replicateM (n+m) $ do
        forM [0..n*m-1] $ \i -> do
          a <- readArray as (i `mod` n)
          b <- readArray bs (i `mod` m)

          when (not a && b) $ writeArray as (i `mod` n) True
          when (a && not b) $ writeArray bs (i `mod` m) True

      as' <- getElems as
      bs' <- getElems bs
      return $ and $ as' ++ bs'

  putStrLn $ if check then "Yes" else "No"

module Main where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8  as C
import Data.List
import Data.Maybe

getIntList :: IO [Int]
getIntList = map fst . mapMaybe C.readInt . C.words <$> C.getLine

main :: IO ()
main = do
  n:m:_ <- getIntList
  b:bs <- getIntList
  g:gs <- getIntList
  putStrLn $ if sol n m bs gs then "Yes" else "No"

sol :: Int -> Int -> [Int] -> [Int] -> Bool
sol a b bs gs = d>0 && (d==1 || d==h)
  where
  d = gcd a b
  h = length $ nub $ map (flip mod d) (bs ++ gs)

import Data.List
import qualified Data.Set as Set
import Control.Applicative
import System.IO
import Debug.Trace

main = do
    [n, m] <- map read <$> words <$> getLine
    (_:boys)  <- map read <$> words <$> getLine
    (_:girls) <- map read <$> words <$> getLine

    let loop i boys girls
          | Set.size boys == n
            && Set.size girls == m  = Right ()
          | i > n * m = Left (boys, girls)
          | otherwise = do
            let ib = i `mod` n
                ig = i `mod` m
                hb = Set.member ib boys
                hg = Set.member ig girls

            let (boys', girls')
                  | hb  &&  hg       = (boys, girls)
                  | not hb && not hg = (boys, girls)
                  | hb  && not hg = (boys, Set.insert ig girls)
                  | not hb &&  hg = (Set.insert ib boys, girls)

            loop (i+1) boys' girls'

    let checkpoint boys girls =
          case loop 0 boys girls of
            Right _ -> True
            Left (boys', girls') -> do
              if boys == boys' && girls == girls'
                then False
                else checkpoint boys' girls'

    putStrLn $
      if checkpoint (Set.fromList boys) (Set.fromList girls)
        then "Yes"
        else "No"

import Data.Char
import Data.List
import Data.Int
import Data.Maybe
import Control.Monad
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import Data.Foldable(toList)
import qualified Data.ByteString.Char8 as B

readInt :: IO Int
readInt = head `liftM` readIntList

readIntList :: IO [Int]
readIntList = do
    line <- B.getLine
    let res = map (fst . fromJust . B.readInt) $ B.words line
    return res

readString :: IO String
readString = do
    line <- B.getLine
    return $ B.unpack line

makeStep :: Set.Set (Int, Int) -> ([Bool], [Bool]) -> ([Bool], [Bool])
makeStep goodPairs (boys, girls) =
    (boys', girls')
    where
        n = length boys
        m = length girls
        happyPairs = [(bi, gi) | (b, bi) <- zip boys [0..],
                                 (g, gi) <- zip girls [0..],
                                 (b || g) && (bi, gi) `Set.member` goodPairs]
        happyBoys = Set.fromList $ map fst happyPairs
        happyGirls = Set.fromList $ map snd happyPairs
        boys' = map (`Set.member` happyBoys) [0..n - 1]
        girls' = map (`Set.member` happyGirls) [0..m - 1]

main = do
    [n, m] <- readIntList
    happyBoys <- tail `liftM` readIntList
    happyGirls <- tail `liftM` readIntList
    let boys = map (`elem` happyBoys) [0..n - 1]
    let girls = map (`elem` happyGirls) [0..m - 1]
    let goodPairs = Set.fromList $ map (\d -> (d `mod` n, d `mod` m)) [0..n * m - 1]
    let (boys', girls') = foldr (.) id (replicate (n + m) (makeStep goodPairs))
            $ (boys, girls)
    let allHappy = not (False `elem` (boys' ++ girls'))
    let ans = if allHappy then "Yes" else "No"
    putStrLn $ ans

import Data.List
import qualified Data.Set as Set
import Control.Applicative
import System.IO

main = do
    [n, m] <- map read <$> words <$> getLine
    (_:boys)  <- map read <$> words <$> getLine
    (_:girls) <- map read <$> words <$> getLine

    let loop i boys girls
          | Set.size boys == n
            && Set.size girls == m  = True
          | i > n * m = False
          | otherwise = do
            let ib = i `mod` n
                ig = i `mod` m
                hb = Set.member ib boys
                hg = Set.member ig girls

            let (boys', girls')
                  | hb  &&  hg       = (boys, girls)
                  | not hb && not hg = (boys, girls)
                  | hb  && not hg = (boys, Set.insert ig girls)
                  | not hb &&  hg = (Set.insert ib boys, girls)

            loop (i+1) boys' girls'

    putStrLn $
      if loop 0 (Set.fromList boys) (Set.fromList girls)
        then "Yes"
        else "No"


import Control.Applicative ((<$>))
import Data.Int (Int64)
import Control.Monad (forM_)
import Data.List (intercalate)

main = do
  [n, m] <- map read . words <$> getLine :: IO [Int]
  a <- map read . words <$> getLine :: IO [Int64]
  b <- map read . words <$> getLine :: IO [Int64]
  forM_ (solve a b 1 0) $ \(x, y) -> do
    putStrLn $ intercalate " " $ map show [x, y]

solve :: [Int64] -> [Int64] -> Int64 -> Int64 -> [(Int64, Int64)]
solve _ [] _ _ = []
solve (a:as) (b:bs) n s
  | b <= s + a = (n, b - s) : solve (a:as) bs n s
  | otherwise  = solve as (b:bs) (n + 1) (s + a)

import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.Map as M
import Data.List

main = do
  inp <- fmap B.lines B.getContents
  let as = map readI $ B.words $ inp!!1
  let bs = map readI $ B.words $ inp!!2
  putStrLn $ unlines $ map (\(i,j)->show i++" "++show j) $ solve as bs

readI :: B.ByteString -> Integer
readI s = case B.readInteger s of Just (n,_) -> n

solve :: [Integer] -> [Integer] -> [(Integer,Integer)]
solve as bs =
  map f bs
  where
    m = M.fromList $ zip (scanl (+) 0 as) [0..]

    f x = case M.lookupLT x m of
            Nothing -> error "error"
            Just (k,v)  -> (v+1,x-k)