{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative (Applicative (liftA2))
import Control.Arrow ((>>>))
import Control.Monad (ap, forM)
import Control.Monad.ST (runST)
import Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM, when)
import qualified Data.Array.Base as AR
import qualified Data.ByteString.Char8 as C
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.Word (Word32)
import Debug.Trace (traceShowId, traceShowM)
import GHC.Conc (par, pseq)
import System.Environment (getArgs)

data TC = TC {n :: Int, a :: [Int], b :: [Int]}

solve TC {..} = runST $ do
  ar <- AR.listArrayST (1, n) a
  br <- AR.listArrayST (1, n) b
  let now = tail $ ap (scanl (\(x, y) val -> (y, val)) . (0,) . head) tail $ (map snd . sort $ zip (zip a b) [1 .. n])

  fl <- forM now $ \(p, q) -> do
    a1 <- AR.readArray ar p
    a2 <- AR.readArray ar q
    b1 <- AR.readArray br p
    b2 <- AR.readArray br q

    pure $ a1 > a2 || b1 > b2

  -- traceShowM fl

  if (foldl1 (||) fl)
    then pure [(-1, -1)]
    else filter (/= (-1, -1)) <$> concat <$> (forM [1..n-1] $ \p -> forM [1..n-1] $ \q -> do
      a1 <- AR.readArray ar q
      a2 <- AR.readArray ar (q + 1)
      b1 <- AR.readArray br q
      b2 <- AR.readArray br (q + 1)

      when (a1 > a2 || b1 > b2) ( do
        AR.writeArray ar q a2
        AR.writeArray ar (q + 1) a1
        AR.writeArray br q b2
        AR.writeArray br (q + 1) b1
        )
      pure $ if a1 > a2 || b1 > b2 then (q, q + 1) else (-1, -1))

toAns xs
  | xs == [(-1, -1)] = ["-1"]
  | otherwise = (show $ length xs) : map (\(x, y) -> show x ++ " " ++ show y) xs

main = C.interact $ runScanner scan >>> map solve >>> map toAns >>> concat >>> map C.pack >>> C.unlines

scan =
  numberOf $
    ( do
        n <- int
        a <- n >< int
        b <- n >< int
        pure $ TC n a b
    )

type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

integer :: Scanner Integer
integer = read . C.unpack <$> str

double :: Scanner Double
double = read . C.unpack <$> str

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t then return [] else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

join :: String -> [String] -> String
join _ [] = ""
join _ [x] = x
join delimiter (x : xs) = x ++ delimiter ++ join delimiter xs

isSorted :: [Int] -> Bool
isSorted [] = True
isSorted [_] = True
isSorted (x : xs) = (x <= head xs) && isSorted xs

indexOf' :: Eq t => Int -> t -> [t] -> Int
indexOf' _ _ [] = -1
indexOf' i k (x : xs)
 | (k == x) = i
 | otherwise = indexOf' (i + 1) k xs

indexOf :: Eq t => t -> [t] -> Int
indexOf k a = indexOf' 0 k a

genSwap :: [Int] -> [(Int, Int)]
genSwap a = [(cur, cur - 1) | (from, to) <- zip a [1 .. ], from /= to, cur <- [from, from - 1 .. to + 1]]

sortAndGetPos' :: [Int] -> [Int] -> [Int] -> Int -> ([Int], [Int])
sortAndGetPos' [] aSorted minPos _ = (aSorted, minPos)
sortAndGetPos' a aSorted minPos from = sortAndGetPos' rest aSortedNew minPosNew (from + 1)
 where
  min = minimum a
  index = indexOf min a
  before = take index a
  after = drop (index + 1) a
  rest = before ++ after
  aSortedNew = aSorted ++ [min]
  minPosNew = minPos ++ [index + from]

sortAndGetPos :: [Int] -> ([Int], [Int])
sortAndGetPos a = sortAndGetPos' a [] [] 1

ans = do
 nInput <- getLine
 aInput <- getLine
 bInput <- getLine
 let n = read nInput :: Int
 let a = [read x :: Int | x <- words aInput]
 let b = [read x :: Int | x <- words bInput]
 let ab = [first * 1000 + second | (first, second) <- zip a b]
 let (abSorted, abSortedPos) = sortAndGetPos ab
 let bExtract = [x `mod` 1000 | x <- abSorted]
 if (isSorted bExtract) then do
  let swaps = genSwap abSortedPos
  let swapsStr = join "\r\n" [show first ++ " " ++ show second | (first, second) <- swaps]
  let len = length swaps
  let result = show (length swaps) ++ (if (len > 0) then ("\r\n" ++ swapsStr) else "")
  return result
 else do
  return "-1"

main = do
 tInput <- getLine
 let t = read tInput :: Int
 results <- sequence (replicate t ans)
 putStrLn (join "\r\n" results)

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative (Applicative (liftA2))
import Control.Arrow ((>>>))
import Control.Monad (ap, forM)
import Control.Monad.ST (runST)
import Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM, when)
import qualified Data.Array.Base as AR
import qualified Data.ByteString.Char8 as C
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.Word (Word32)
import Debug.Trace (traceShowId, traceShowM)
import GHC.Conc (par, pseq)
import System.Environment (getArgs)

data TC = TC {n :: Int, a :: [Int], b :: [Int]}

solve TC {..} = runST $ do
  ar <- AR.listArrayST (1, n) a
  br <- AR.listArrayST (1, n) b
  let now = tail $ ap (scanl (\(x, y) val -> (y, val)) . (0,) . head) tail $ (map snd . sort $ zip (zip a b) [1 .. n])

  fl <- forM now $ \(p, q) -> do
    a1 <- AR.readArray ar p
    a2 <- AR.readArray ar q
    b1 <- AR.readArray br p
    b2 <- AR.readArray br q
    pure $ a1 > a2 || b1 > b2

  if (foldl1 (&&) fl)
    then pure [(-1, -1)]
    else filter (/= (-1, -1)) <$> concat <$> (forM [1..n-1] $ \p -> forM [1..n-1] $ \q -> do
      a1 <- AR.readArray ar q
      a2 <- AR.readArray ar (q + 1)
      b1 <- AR.readArray br q
      b2 <- AR.readArray br (q + 1)

      when (a1 > a2 || b1 > b2) ( do
        AR.writeArray ar q a2
        AR.writeArray ar (q + 1) a1
        AR.writeArray br q b2
        AR.writeArray br (q + 1) b1
        )
      pure $ if a1 > a2 || b1 > b2 then (q, q + 1) else (-1, -1))

toAns xs
  | xs == [(-1, -1)] = ["-1"]
  | otherwise = (show $ length xs) : map (\(x, y) -> show x ++ " " ++ show y) xs

main = C.interact $ runScanner scan >>> map solve >>> map toAns >>> concat >>> map C.pack >>> C.unlines

scan =
  numberOf $
    ( do
        n <- int
        a <- n >< int
        b <- n >< int
        pure $ TC n a b
    )

type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

integer :: Scanner Integer
integer = read . C.unpack <$> str

double :: Scanner Double
double = read . C.unpack <$> str

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t then return [] else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative (Applicative (liftA2))
import Control.Arrow ((>>>))
import Control.Monad (ap, forM)
import Control.Monad.ST (runST)
import Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM, when)
import qualified Data.Array.Base as AR
import qualified Data.ByteString.Char8 as C
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.Word (Word32)
import Debug.Trace (traceShowId, traceShowM)
import GHC.Conc (par, pseq)
import System.Environment (getArgs)

data TC = TC {n :: Int, a :: [Int], b :: [Int]}

solve TC {..} = runST $ do
  ar <- AR.listArrayST (1, n) a
  br <- AR.listArrayST (1, n) b
  let now = tail $ ap (scanl (\(x, y) val -> (y, val)) . (0,) . head) tail $ (map snd . sort $ zip (zip a b) [1 .. n])

  fl <- forM now $ \(p, q) -> do
    a1 <- AR.readArray ar p
    a2 <- AR.readArray ar q
    b1 <- AR.readArray br p
    b2 <- AR.readArray br q
    pure $ a1 > a2 || b1 > b2

  if (foldl1 (&&) fl)
    then pure [(-1, -1)]
    else filter (/= (-1, -1)) <$> concat <$> (forM [1..n-1] $ \p -> forM [1..n-1] $ \q -> do
      a1 <- AR.readArray ar q
      a2 <- AR.readArray ar (q + 1)
      b1 <- AR.readArray br p
      b2 <- AR.readArray br q

      AR.writeArray ar q a2
      AR.writeArray ar (q + 1) a1
      AR.writeArray br q b2
      AR.writeArray br (q + 1) b1

      pure $ if a1 > a2 || b1 > b2 then (q, q + 1) else (-1, -1))

toAns xs
  | xs == [(-1, -1)] = ["-1"]
  | otherwise = (show $ length xs) : map (\(x, y) -> show x ++ " " ++ show y) xs

main = C.interact $ runScanner scan >>> map solve >>> map toAns >>> concat >>> map C.pack >>> C.unlines

scan =
  numberOf $
    ( do
        n <- int
        a <- n >< int
        b <- n >< int
        pure $ TC n a b
    )

type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

integer :: Scanner Integer
integer = read . C.unpack <$> str

double :: Scanner Double
double = read . C.unpack <$> str

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t then return [] else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative (Applicative (liftA2))
import Control.Arrow ((>>>))
import Control.Monad (ap, forM)
import Control.Monad.ST (runST)
import Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM, when)
import qualified Data.Array.Base as AR
import qualified Data.ByteString.Char8 as C
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.Word (Word32)
import Debug.Trace (traceShowId, traceShowM)
import GHC.Conc (par, pseq)
import System.Environment (getArgs)

data TC = TC {n :: Int, a :: [Int], b :: [Int]}

solve TC {..} = runST $ do
  ar <- AR.listArrayST (1, n) a
  br <- AR.listArrayST (1, n) b
  let now = tail $ ap (scanl (\(x, y) val -> (y, val)) . (0,) . head) tail $ (map snd . sort $ zip (zip a b) [1 .. n])

  fl <- forM now $ \(p, q) -> do
    a1 <- AR.readArray ar p
    a2 <- AR.readArray ar q
    b1 <- AR.readArray br p
    b2 <- AR.readArray br q
    pure $ a1 > a2 || b1 > b2

  if (foldl1 (&&) fl)
    then pure [(-1, -1)]
    else filter (/= (-1, -1)) <$> concat <$> (forM [1..n-1] $ \p -> forM [1..n-1] $ \q -> do
      a1 <- AR.readArray ar q
      a2 <- AR.readArray ar (q + 1)
      b1 <- AR.readArray br p
      b2 <- AR.readArray br q
      -- when (a1 > a2 || b1 > b2) ( do
      --   AR.writeArray a p e
      -- )
      pure $ if a1 > a2 || b1 > b2 then (q, q + 1) else (-1, -1))

toAns xs
  | xs == [(-1, -1)] = ["-1"]
  | otherwise = (show $ length xs) : map (\(x, y) -> show x ++ " " ++ show y) xs

main = C.interact $ runScanner scan >>> map solve >>> map toAns >>> concat >>> map C.pack >>> C.unlines

scan =
  numberOf $
    ( do
        n <- int
        a <- n >< int
        b <- n >< int
        pure $ TC n a b
    )

type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

integer :: Scanner Integer
integer = read . C.unpack <$> str

double :: Scanner Double
double = read . C.unpack <$> str

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t then return [] else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)


import Data.List

second :: [Int] -> Int
second a = a !! 1

solve :: [Int] -> Int
solve = second . sort

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

-- pragmas.hs  {{{
-- vim: foldmethod=marker
{-# LANGUAGE AllowAmbiguousTypes        #-}
{-# LANGUAGE BinaryLiterals             #-}
{-# LANGUAGE ConstraintKinds            #-}
{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE DeriveFoldable             #-}
{-# LANGUAGE DeriveFunctor              #-}
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE DeriveTraversable          #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs               #-}
{-# LANGUAGE LambdaCase                 #-}
{-# LANGUAGE MagicHash                  #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE MultiWayIf                 #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE StandaloneDeriving         #-}
{-# LANGUAGE TupleSections              #-}
{-# LANGUAGE TypeApplications           #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE TypeInType                 #-}
{-# LANGUAGE TypeOperators              #-}
{-# LANGUAGE UnboxedTuples              #-}
{-# LANGUAGE UndecidableInstances       #-}
-- pragmas.hs }}}
module Main where

import           Control.Monad            (replicateM_)
import           Data.Array               (Array, (!))
import qualified Data.ByteString          as BS
import qualified Data.ByteString.Char8    as C
import qualified Data.ByteString.Internal as BSI
import qualified Data.IntMap              as IntMap
import           Data.Ix                  (Ix)
import           Data.List
import           Debug.Trace              (trace)

solve :: [Int] -> Int
solve = (!!1) . sort

doCase :: IO ()
doCase = do
  xs <- getInts
  print $ solve xs

main :: IO ()
main = getInt >>= flip replicateM_ doCase

readInt :: C.ByteString -> Int
readInt s = let Just (i,_) = C.readInt s in i :: Int

readInt2 :: C.ByteString -> (Int, Int)
readInt2 u = (a, b)
  where
  Just (a,v) = C.readInt u
  Just (b,_) = C.readInt (C.tail v)

readInts :: C.ByteString -> [Int]
readInts str = readInt <$> BS.split (BSI.c2w ' ') str

getInt :: IO Int
getInt  = readInt <$> C.getLine

getInt2 :: IO (Int, Int)
getInt2 = readInt2 <$> C.getLine

getInts :: IO [Int]
getInts = readInts <$> C.getLine


import Control.Monad

solve :: [[Int]] -> Int
solve a = maximum $ map minimum a

mapInt :: [String] -> [Int]
mapInt a = map read a

main :: IO()
main = do
  [m, n] <- liftM (map read . words) getLine
  lines <- replicateM m getLine
  print $ solve $ map (mapInt .words) lines

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> (-n)
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input = show answer
    where
        (n:m:asnums) = map fastRead (words input)
        streets = streeter asnums
            where
                streeter [] = []
                streeter xs = c:(streeter rest)
                    where
                        (c,rest) = splitAt (fromIntegral m) xs

        answer = maximum (map minimum streets)

module Main where

import Data.List
import Data.String
import Data.Maybe
import Data.Either
import Control.Monad
import Control.Applicative
import Control.Arrow

main :: IO()
main = do
    [n,_] <- liftM (map (read::String -> Int).words) getLine
    arr <- forM [1..n] (\_ -> liftM (map (read::String -> Int).words) getLine)
    print $ foldl max 0 $ map (foldl min (10^9+1)) arr

import Control.Applicative

solve :: [[Int]] -> Int
solve = maximum . (map minimum)

main :: IO ()
main = do
  [n, m] <- map read . words <$> getLine
  css <- mapM (\_ -> map read . words <$> getLine) [1..n]
  print $ solve css

convert :: String -> [[Int]]
convert s = map (map read . words) $ lines s

solve :: [[Int]] -> Int
solve x = maximum $ map minimum x

main = do
    input <- getContents
    print $ solve (tail $ convert input)

module Main where

dinnerWithEmma = foldr1 max . map (foldr1 min)

processRaw = map processLine . tail . lines
    where processLine = map (read :: String -> Int) . words

main = do
    raw <- getContents
    print . dinnerWithEmma . processRaw $ raw

main = interact $ show. maximum . map (minimum . map (read ::String->Int). words) . tail . lines

import Control.Applicative ((<$>))

main = do
  getLine
  a <- map (map read . words) . lines <$> getContents :: IO [[Int]]

  print . maximum $ map minimum a

main = getContents >>= (print. foldr max (-100000000) . map (foldr min (1100000000). map read . words). tail. lines)

import Prelude
import Control.Monad
import Data.Functor
import Data.List

readIntegers :: IO [Integer]
readIntegers = map (read :: String -> Integer) . words <$> (getLine :: IO String)

getCost :: Integer -> Integer -> [[Integer]] -> Integer
getCost rows cols grid = maximum (map minimum grid)

main :: IO ()
main = do
    dimensions <- readIntegers
    rows <- return (dimensions!!0)
    cols <- return (dimensions!!1)
    grid <- replicateM (fromInteger rows) readIntegers
    putStrLn (show (getCost rows cols grid))

import Control.Monad

solve :: [[String]] -> String
solve a = maximum $ map minimum a

main :: IO()
main = do
  [m, n] <- liftM (map read . words) getLine

  lines <- replicateM m getLine
  putStrLn $ solve (map words lines)


import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import qualified Data.Set as S

import Data.Maybe
import Control.Monad

import Data.List

solve [p1, p2, p3] =
    let s1 = S.fromList p1
        s2 = S.fromList p2
        s3 = S.fromList p3
        useless = s1 `S.intersection` s2 `S.intersection` s3
    in solve1 [s1 S.\\ useless, s2 S.\\ useless, s3 S.\\ useless]

solve1 [p1, p2, p3] = C.unwords . map (C.pack . show) $ [calc p1 p2 p3, calc p2 p1 p3, calc p3 p1 p2]

calc cur ot1 ot2 = inter1 + inter2 + 3 * uniq
    where inter1 = S.size $ cur `S.intersection` ot1
          inter2 = S.size $ cur `S.intersection` ot2
          uniq = S.size $ cur S.\\ (ot1 `S.union` ot2)

work = do
    n <- C.getLine
    t1 <- C.getLine
    t2 <- C.getLine
    t3 <- C.getLine

    C.putStrLn $ solve [ C.words x | x <- [t1, t2, t3] ]

main = do
    t <- C.getLine

    replicateM_ (fst $ fromJust $ C.readInt t) work

{-#LANGUAGE ScopedTypeVariables#-}
import Data.Char (isDigit)
import Data.Set (Set, fromList, member)

main = do
    input <- getContents
    let parsed = removeDigits (lines input)
    let result = parseTriples parsed
    mapM_ putStrLn result

removeDigits :: [String] -> [String]
removeDigits [] = []
removeDigits (x:xs)
    | all isDigit x = removeDigits xs
    | otherwise     = [x] ++ removeDigits xs

-- Gets eachs persons input line, and parses it to a [String], which can be used in checkRound
parseTriples :: [String] -> [String]
parseTriples [] = []
parseTriples (p1:p2:p3:rest) = [(checkRound (words p1) (words p2) (words p3))] ++ parseTriples rest

-- Gets the score for each person, and outputs the score on the format: "p1 p2 p3"
checkRound :: [String] -> [String] -> [String] -> String
checkRound p1 p2 p3 = do
    let p1s = fromList p1
    let p2s = fromList p2
    let p3s = fromList p3
    let p1Score = getScore p1 p2s p3s
    let p2Score = getScore p2 p1s p3s
    let p3Score = getScore p3 p1s p2s
    (show p1Score) ++ " " ++ (show p2Score) ++ " " ++ (show p3Score)

-- Takes each persons words, and outputs the score for the first person
getScore :: [String] -> Set String -> Set String -> Int
getScore [] _ _ = 0
getScore (x:xs) y z
    | (member x y) && (member x z) = 0 + getScore xs y z
    | (member x y) || (member x z) = 1 + getScore xs y z
    | otherwise                    = 3 + getScore xs y z

import Data.Map (Map(..))
import qualified Data.Map as M
import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = getLine >>
        wl >>=
        \w1 -> wl >>=
        \w2 -> wl >>=
        \w3 -> let cm = score w1 w2 w3
                   a = maybe 0 id (M.lookup 1 cm)
                   b = maybe 0 id (M.lookup 2 cm)
                   c = maybe 0 id (M.lookup 3 cm)
               in
                 putStrLn $ show a ++ " " ++ show b ++ " " ++ show c
  where wl = words <$> getLine

score :: [String] -> [String] -> [String] -> Map Int Int
score w1 w2 w3 = let m :: Map String [Int]
                     m = M.empty
                     iF s i = M.insertWith (++) s [i]
                     w = zip w1 (repeat 1) ++ zip w2 (repeat 2) ++ zip w3 (repeat 3)
                     f cm [i] = M.adjust (3+) i cm
                     f cm [i, j] = M.adjust (1+) i (M.adjust (1+) j cm)
                     f cm _ = cm
                 in
                   M.foldl f (M.fromList [(1, 0), (2, 0), (3, 0)])
                   (foldl (\m (s, i) -> iF s i m) m w)

import Control.Monad
import Data.Set

main = do
    t <- read <$> getLine
    forM_ [1..t] $ const solve

solve = do
    getLine
    [nums1, nums2, nums3] <-
        (fmap . fmap) (fromList . words) (forM [1..3] $ const getLine)
    putStrLn $ unwords (fmap show [
        score nums1 nums2 nums3,
        score nums2 nums1 nums3,
        score nums3 nums1 nums2 ])
    return ()

score xs ys zs =
    sum $ fmap (\x -> trans $ fromEnum (member x ys) + fromEnum (member x zs)) (toList xs)
    where
        trans x
            | x == 0 = 3
            | x == 1 = 1
            | x == 2 = 0
            | otherwise = undefined

{-# LANGUAGE CPP, ScopedTypeVariables, TypeApplications, TupleSections #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Control.Monad.ST
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
-- import qualified Data.ByteString.Lazy.Char8 as B
import System.IO
import Control.Monad.Trans.State
import Control.Monad.Trans
import Data.Maybe
import Data.Bits
import Prelude hiding (reverse)
import Data.List hiding (lookup)
import Debug.Trace
import Data.Char
import Data.Map (Map, fromListWith)
import qualified Data.Map as M

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

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

str = string7

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

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

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

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

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
#ifdef LOCAL
  handle <- openFile "input" ReadMode
  inp <- P.hGetContents handle
#else
  inp <- P.getContents
#endif
  let outp = evalState tloop inp
  P.putStr $ toLazyByteString outp

tloop :: SP Builder
tloop = do
  t <- getInt
  -- let t = 1
  fmap mconcat $ replicateM t $ solve

solve :: SP Builder
solve = do
  n <- getInt
  a <- replicateM n getNext
  b <- replicateM n getNext
  c <- replicateM n getNext
  let
    combined = a ++ b
    -- tst = map (,1) combined
    counter = fromListWith (+) . map (,1) $ (a ++ b ++ c)
    score :: P.ByteString -> Int
    score s = case M.lookup s counter of
      Nothing -> 0
      Just x -> case x of
        1 -> 3
        2 -> 1
        3 -> 0
    fun = sum . map score
    ansa = fun a
    ansb = fun b
    ansc = fun c
  pure $ putInts [ansa, ansb, ansc]

import Control.Monad (forM_)
import Data.List
import Debug.Trace (trace)
import qualified Data.Map as M

readInts = getLine >>= pure . map read . words
hm 3 = 0
hm 2 = 1
hm 1 = 3

main = do
    [n'] <- readInts
    forM_ [1..n'] (\_ -> do
        getLine
        a <- getLine >>= pure . words
        b <- getLine >>= pure . words
        c <- getLine >>= pure . words
        let m = M.fromList . map (\l -> (head l, length l)) . group . sort $ a ++ b ++ c
        forM_ [a,b,c] (\l -> do
            putStr . show . sum . map (hm . (m M.!)) $ l
            putStr " ")
        putStrLn "" )

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import qualified Data.Set as S

import Data.Maybe
import Control.Monad

import Data.List

solve p =
    let s = map S.fromList p
        useless = (s !! 0) `S.intersection` (s !! 1) `S.intersection` (s !! 2)
    in solve1 $ map (\x -> x S.\\ useless) s

solve1 [p1, p2, p3] = C.unwords . map (C.pack . show) $ [calc p1 p2 p3, calc p2 p1 p3, calc p3 p1 p2]

calc cur ot1 ot2 = inter1 + inter2 + 3 * uniq
    where inter1 = S.size $ cur `S.intersection` ot1
          inter2 = S.size $ cur `S.intersection` ot2
          uniq = S.size $ cur S.\\ (ot1 `S.union` ot2)

work = do
    n <- C.getLine
    t1 <- C.getLine
    t2 <- C.getLine
    t3 <- C.getLine

    C.putStrLn $ solve [ C.words x | x <- [t1, t2, t3] ]

main = do
    t <- C.getLine

    replicateM_ (fst $ fromJust $ C.readInt t) work

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import qualified Data.Map.Strict as M

import Data.Maybe
import Control.Monad

import Data.List

--solve p = solve1 (map countElems p)
--solve :: [C.ByteString] -> [C.ByteString]
solve p = solve1 $ map countElems p

solve1 [p1, p2, p3] = unwords . map show $ [calc p1 p2 p3, calc p2 p1 p3, calc p3 p1 p2]

calc cur ot1 ot2 = inter1 + inter2 + 3 * uniq
    where inter1 = M.size $ cur `M.intersection` ot1
          inter2 = M.size $ cur `M.intersection` ot2
          uniq = M.size $ cur M.\\ (ot1 `M.union` ot2)

countElems = M.fromListWith (+) . flip zip (repeat 1)

del x y z = length $ x \\ (y `union` z)
inter x y = length $ x `intersect` y

work = do
    n <- C.getLine
    t1 <- C.getLine
    t2 <- C.getLine
    t3 <- C.getLine

    putStrLn $ solve [ C.words x | x <- [t1, t2, t3] ]

main = do
    t <- C.getLine

    replicateM_ (fst $ fromJust $ C.readInt t) work

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import qualified Data.Map.Strict as M

import Data.Maybe
import Control.Monad

import Data.List

--solve p = solve1 (map countElems p)
--solve :: [C.ByteString] -> [C.ByteString]
solve p = solve1 $ map countElems p

solve1 [p1, p2, p3] = [calc p1 p2 p3, calc p2 p1 p3, calc p3 p1 p2]

calc cur ot1 ot2 = inter1 + inter2 + 3 * uniq
    where inter1 = M.size $ cur `M.intersection` ot1
          inter2 = M.size $ cur `M.intersection` ot2
          uniq = M.size $ cur M.\\ (ot1 `M.union` ot2)

countElems = M.fromListWith (+) . flip zip (repeat 1)

del x y z = length $ x \\ (y `union` z)
inter x y = length $ x `intersect` y

work = do
    n <- C.getLine
    t1 <- C.getLine
    t2 <- C.getLine
    t3 <- C.getLine

    print $ solve [ C.words x | x <- [t1, t2, t3] ]

main = do
    t <- C.getLine

    replicateM_ (fst $ fromJust $ C.readInt t) work


module Main where

import           Control.Monad
import           Data.List

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

solvet :: IO ()
solvet = do
  noTypes <- read <$> getLine
  types <- map read . words <$> getLine
  let (maxmax, maxx) = twoMaxes types (0, 0)
  let res
        | noTypes == 1 =
          if head types > 1
            then "NO"
            else "YES"
        | maxmax - maxx > 1 = "NO"
        | otherwise = "YES"
  putStrLn res

twoMaxes :: Ord a => [a] -> (a, a) -> (a, a)
twoMaxes [] (a, b) = (a, b)
twoMaxes (x:xs) (a, b)
  | x > a = twoMaxes xs (x, a)
  | x > b = twoMaxes xs (a, x)
  | otherwise = twoMaxes xs (a, b)


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

main = getLine >>= flip replicateM_ test . read

test = do
    n <- read <$> getLine
    let ds = zipWith subtract <*> tail $ solve n
    print $ length ds
    putStrLn $ unwords . map show $ ds

solve n = sort $ f 1 n

f _ 0 = []
f i n
    | i > n = [n]
    | otherwise = i : f (2 * i) (n - i)

powersOf2 :: [Int]
powersOf2 = go 1
    where
        go aux = aux : go (aux*2)

diff :: Int -> [Int] -> [Int]
diff excess (a:as)
    | excess <= a   = [excess]
    | otherwise     = a: diff (excess-a) as

numberOfDays :: Int -> (Int, Int)
numberOfDays n = (d, n-2^d)
    where
        d = floor . logBase 2 . fromIntegral $ n

increments :: [Int] -> [Int]
increments (a1:a2:as) = (a2-a1): increments (a2:as)
increments _ = []

solve :: Int -> [String]
solve n = [show d, unwords $ map show inc]
    where
        (d,e) = numberOfDays n
        delta = diff e powersOf2 ++ [0,0..]
        count = 1 : take d (zipWith (+) delta powersOf2)
        inc = increments count

test = solve 9

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


module Main where

readI :: String -> Int
readI = read

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

main = do
    n <- getLine >>= return . readI
    ps <- getContents >>= return . (map readL) . (take n) . lines
    print $ solve n ps

solve n ps = inter pairs y0 l r where

    pairs = tail (zip ps (tail ps ++ [head ps]))

    a = head ps
    b = ps!!1
    l = min (head a) (head b)
    r = max (head a) (head b)
    y0 = a!!1

    inter []  _ l r = if l > r then 0 else (floor r) - (ceiling l) + 1

    inter (([x1,y1], [x2,y2]):ps) y0 l r = case compare dy 0 of
        EQ -> if dx0 <= 0 then inter ps y0 l r
                          else 0
        GT -> inter ps y0 (max l x0) r
        LT -> inter ps y0 l (min x0 r)
        where
            dy = y2 - y1
            dx = x2 - x1
            c = dx*y1 - dy*x1
            dx0 = dx*y0 - c
            x0 = dx0 / dy

module Main where

readI :: String -> Int
readI = read

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

main = do
    n <- getLine >>= return . readI
    ps <- getContents >>= return . (map readL) . (take n) . lines
    print $ solve n ps

solve n ps = inter pairs y0 l r where

    pairs = tail (zip ps (tail ps ++ [head ps]))

    a = head ps
    b = ps!!1
    l = min (head a) (head b)
    r = max (head a) (head b)
    y0 = a!!1

    inter _   _ l r |  l > r  = 0
    inter []  _ l r           = (floor r) - (ceiling l) + 1

    inter (([x1,y1], [x2,y2]):ps) y0 l r = case compare dy 0 of
        EQ -> if dx0 <= 0 then inter ps y0 l r
                          else 0
        GT -> inter ps y0 (max l x0) r
        LT -> inter ps y0 l (min x0 r)
        where
            dy = y2 - y1
            dx = x2 - x1
            c = dx*y1 - dy*x1
            dx0 = dx*y0 - c
            x0 = dx0 / dy


main = do getLine; getLine >>= putStr . show . gao . map (fromInteger . read) . words
gao [0, 0] = 0
gao [0, _] = 1
gao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else j / i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0] where
	(a:b:c:_) = x
	f _ _ [] = 0
	f a b (h:t) = if a == h then f (a*b) b t else f a b t + 1

main = do getLine; getLine >>= putStr . show . gao . map read . words
gao x = if length x < 3 then 0 else minimum $ 2:[f j (div i j) x | (i, j) <- [(c, b), (c, a), (b, a)], j /= 0, mod i j == 0] where
	(a:b:c:_) = x
	f _ _ [] = 0
	f a b (h:t) = if a == h then f (a*b) b t else f a b t + 1

main = do getLine; getLine >>= putStr . show . gao . map read . words
gao [0, 0] = 0
gao [0, _] = 1
gao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else div j i) x | (i, j) <- [(b, c), (a, c), (a, b)], j == 0 || i /= 0 && mod j i == 0] where
	(a:b:c:_) = x
	f _ _ [] = 0
	f a b (h:t) = if a == h then f (a*b) b t else f a b t + 1

main = do getLine; getLine >>= putStr . show . gao . map read . words
gao x = if length x < 3 then 0 else minimum $ 2:[f i (if j == 0 then 0 else div j i) x | (i, j) <- [(b, c), (a, c), (a, b)], i /= 0 && mod j i == 0 || j == 0] where
	(a:b:c:_) = x
	f _ _ [] = 0
	f a b (h:t) = if a == h then f (a*b) b t else f a b t + 1


module Main (main) where

import Data.List

readInt :: String -> Int
readInt = read

main = do
    input <- getLine
    let [a, b] = map readInt $ take 2 $ words input
    input <- getContents
    let picture = take a $ lines input
    let good = goodPuzzles a b picture
    print $ length good
    printPair $ minimumBy compareXY good where

    goodPuzzles a b picture = filter isGoodPuzzle pairs where

        isGoodPuzzle (n, m) = isGood $ sort $ makeSprites n m where
            isGood [s]    = True
            isGood (s:ss) = if s == (head ss) then False else isGood ss

        makeSprites n m = makeSplitList a b picture [] where
            makeSplitList 0  _  _   acc = acc
            makeSplitList sn sm pic acc =
                makeSplitList (sn-n) sm (drop n pic)
                              (makeSplit sm (take n pic) [] ++ acc)
            makeSplit 0  _   acc = acc
            makeSplit sm pic acc =
                makeSplit (sm-m) (map (drop m) pic)
                                 (map concat (rotates n m (map (take m) pic)) ++ acc)
            rotates n m pic = if n == m
                then nub [pic, rot90, rot180, rot270]
                else nub [pic, rot180] where
                    rot90 = transpose reversed
                    rot180 = map reverse reversed
                    rot270 = reverse (transpose pic)
                    reversed = reverse pic

        pairs = [(x, y) | x <- divisors a, y <- divisors b]
        divisors n = [x | x <- [1..n], mod n x == 0]

    compareXY (x1, y1) (x2, y2) = case compare (x1*y1) (x2*y2) of
        LT -> LT
        GT -> GT
        EQ -> compare x1 x2

    printPair (x, y) = do
        putStrLn $ show x ++ " " ++ show y

import Control.Monad
import Data.List

explode' i x = take i . map (take x) . iterate (drop x)
explode :: Int -> Int -> Int -> Int -> [String] -> [[String]]
explode i x j y = concatMap (map (map head) . take j . iterate (map tail)) . explode' i x . map (explode' j y)
rotate = reverse . transpose
std = minimum . take 4 . iterate rotate

gao r c s = [[x * y, x, y] |
	x <- [1 .. r], i <- [div r x], i * x == r,
	y <- [1 .. c], j <- [div c y], j * y == c,
	(==i*j) $ length $ group $ sort $ map std $ explode i x j y s]

main = do
	[r, c] <- fmap (map read . words) getLine
	s <- replicateM r getLine
	putStrLn $ let a = gao r c s in unwords $ map show $ (length a:) $ tail $ minimum a

import Control.Monad
import Data.List

explode' i x = take i . map (take x) . iterate (drop x)
explode i x j y = concatMap (map (map head) . take j . iterate (map tail)) . explode' i x . map (explode' j y)
rotate = reverse . transpose
std = minimum . take 4 . iterate rotate

gao r c s = [[x * y, x, y] |
	x <- [1 .. r], i <- [div r x], i * x == r,
	y <- [1 .. c], j <- [div c y], j * y == c,
	(==i*j) $ length $ group $ sort $ map std $ explode i x j y s]

main = do
	[r, c] <- fmap (map read . words) getLine
	s <- replicateM r getLine
	putStrLn $ let a = gao r c s in unwords $ map show $ (length a:) $ tail $ minimum a

{-# LANGUAGE ViewPatterns #-}

import Data.Array.IArray
import Data.List
import Text.Printf
import Debug.Trace

type Block = Array (Int, Int) Char

size :: Block -> (Int, Int)
size blk =
    let (_, (h, w)) = bounds blk
    in (h+1,w+1)

rotate :: Block -> Block
rotate blk =
    let (size -> (h, w)) = blk
    in listArray ((0,0), (w-1,h-1))
                 [blk ! (c, w-r-1) | r <- [0..w-1], c <- [0..h-1]]

minrep :: Block -> Block
minrep blk = minimum $ take 4 $ iterate rotate blk

valid :: [Block] -> Bool
valid list =
    let sorted = sort $ map minrep list
    in and $ zipWith (/=) sorted (tail sorted)

split :: Block -> Int -> Int -> [Block]
split blk a b =
    let (size -> (h, w)) = blk
    in [listArray ((0,0), (a-1,b-1))
                  [blk ! (h'*a+a', w'*b+b') | a' <- [0..a-1], b' <- [0..b-1]]
        | h' <- [0..h `div` a - 1], w' <- [0..w `div` b - 1]]

solve :: Block -> [[Block]]
solve blk =
    let (size -> (h, w)) = blk
        divable x y = x `mod` y == 0
        allblk = [split blk a b | a <- filter (divable h) [1..h],
                                  b <- filter (divable w) [1..w]]
    in filter valid allblk

cmp :: [Block] -> [Block] -> Ordering
cmp (a:_) (b:_) =
    let (size -> (ha, wa)) = a
        (size -> (hb, wb)) = b
    in case compare (ha * wa) (hb * wb) of
         EQ -> compare ha hb
         ne -> ne

readBlk :: Int -> Int -> IO Block
readBlk w h = do
    list <- (concat . words) `fmap` getContents
    return $ listArray ((0,0), (w-1,h-1)) list

main = do
    [w, h] <- (map read . words) `fmap` getLine
    blk <- readBlk w h

    let ans = solve blk
    printf "%d\n" (length ans)

    let (size -> (x, y)) = head $ minimumBy cmp ans
    printf "%d %d\n" x y

module Main (main) where

import Data.List

readInt :: String -> Int
readInt = read

main = do
    input <- getLine
    let [a, b] = map readInt $ take 2 $ words input
    input <- getContents
    let picture = take a $ lines input
    let good = goodPuzzles a b picture
    print $ length good
    printPair $ minimumBy compareXY good where

    goodPuzzles a b picture = filter isGoodPuzzle pairs where

        isGoodPuzzle (n, m) = isGood $ sort $ makeSprites n m where
            isGood [s]    = True
            isGood (s:ss) = if s == (head ss) then False else isGood ss

        makeSprites n m = makeSplitList a b picture [] where
            makeSplitList 0  _  _   acc = acc
            makeSplitList sn sm pic acc =
                makeSplitList (sn-n) sm (drop n pic)
                              (acc ++ makeSplit sm (take n pic) [])
            makeSplit 0  _   acc = acc
            makeSplit sm pic acc =
                makeSplit (sm-m) (map (drop m) pic)
                                 ((concat (map (take m) pic)):acc)

        pairs = [(x, y) | x <- divisors a, y <- divisors b]
        divisors n = [x | x <- [1..n], mod n x == 0]

    compareXY (x1, y1) (x2, y2) = case compare (x1*y1) (x2*y2) of
        LT -> LT
        GT -> GT
        EQ -> compare x1 x2

    printPair (x, y) = do
        putStrLn $ show x ++ " " ++ show y


{-# LANGUAGE NPlusKPatterns #-}
module Main (main) where

import Control.Monad (liftM2, liftM3, mapM_)

type Query = (Integer, Integer, Integer)

main :: IO ()
main = do
    t <- getInteger
    queries <- getQueries t
    mapM_ (print . calculate) queries

getInteger :: IO Integer
getInteger = fmap read getLine

getQueries :: Integer -> IO [Query]
getQueries 0 = return []
getQueries (n + 1) = liftM2 (:) getQuery (getQueries n)

getQuery :: IO Query
getQuery = fmap ((\[a, b, k] -> (a, b, k)) . map read . words) getLine

calculate :: Query -> Integer
calculate (a, b, k) = let (q, r) = quotRem k 2
                      in q * (a - b) + r * a

{-# LANGUAGE ScopedTypeVariables #-}

import           Data.Int

main :: IO ()
main = readLn >>= ntimes solve

ntimes :: IO () -> Int -> IO ()
ntimes _  0 = return ()
ntimes io n = io >> ntimes io (n - 1)

solve :: IO ()
solve = do
    [a, b, k] :: [Int64] <- map read . words <$> getLine
    let ans = k `div` 2 * (a - b)
    if k `mod` 2 /= 0 then print $ ans + a else print ans

main :: IO ()
main = interact $ processInput.parseInput

readInteger :: String -> Integer
readInteger = read

parseInput :: String -> [[Integer]]
parseInput inputFromFile = tail [[readInteger x | x <- words line] | line <- lines inputFromFile]

calcFunc :: Integer -> Integer -> Integer -> Integer
calcFunc a b k
  | odd k = (a-b)*((k-1)`div` 2) + a
  | otherwise = (a - b)*(k`div` 2)

processInput :: [[Integer]] -> String
processInput [] = ""
processInput (x:xs) = (show $ calcFunc (x !! 0) (x !! 1) (x !! 2))++ "\n" ++ processInput xs

solve :: [Integer] -> Integer
solve (a:b:k:_) = (a - b) * (k `div` 2) + a * (k `mod` 2)

main :: IO()
main = do
  n <- getLine
  x <- getContents
  mapM_ (putStrLn . show . solve . (map (read::String->Integer)) . words) $ lines x

readInteger :: String -> Integer
readInteger = read

parseInput :: String -> [[Integer]]
parseInput file
    = tail [ [readInteger word | word <- words line] | line <- lines file ]

processInput :: [[Integer]] -> [Integer]
processInput [] = []
processInput ([right, left, steps] : others)
    = pos : (processInput others)
      where pos = if even steps then total else total + right
            total = (right - left) * (steps `div` 2)

showOutput :: [Integer] -> String
showOutput [] = ""
showOutput (x:xs) = (show x) ++ "\n" ++ (showOutput xs)

main = interact $ showOutput . processInput . parseInput

getFrogs :: Int -> IO [[Integer]]
getFrogs 0 = do return []
getFrogs t = do
    line <- getLine
    let xs = map (\s -> read s :: Integer) (words line)
    more <- getFrogs (t - 1)
    return (xs : more)

main = do
    line <- getLine
    let n = read line :: Int
    frogs <- getFrogs n
    mapM print (positions frogs)

positions :: [[Integer]] -> [Integer]
positions [] = []
positions ([right, left, steps] : frogs)
    = pos : (positions frogs)
      where pos = if even steps then total else total + right
            total = (right - left) * (steps `div` 2)

f::[String]->[Integer]
f []=[]
f (x:xs)=let (a:b:k:[])=map read (words x)::[Integer]
         in if k `mod` 2==1 then ((a-b)*(k `div` 2)+a):(f xs) else (a-b)*(k `div` 2):f xs

main = do
       a<-getLine
       b<-getContents
       let xs=lines b
       mapM_ putStrLn $ map show $  f xs

import Control.Monad
import Data.Bits

main = getLine
   >>= readQueries . read
   >>= putStrLn . calc

readQueries :: Int -> IO [String]
readQueries t = mapM (\_ -> getLine) [1..t]

calc :: [String] -> String
calc lines = foldr go "" lines
  where go line ans = show res ++ "\n" ++ ans
          where [s1, s2, s3] = words line
                a = read s1
                b = read s2
                k = read s3
                halfK = div k 2
                res = ((.&.) k 1 + halfK) * a - (b * halfK) :: Integer

import Prelude
import Data.List
import Text.Printf
import Control.Monad
import Data.Ratio
import Data.Int
import Data.Functor

solve :: Int64 -> Int64 -> Int64 -> Int64
solve a b k = k1 * a - k2 * b
    where
        k1 = k - k2
        k2 = k `div` 2

main :: IO ()
main = do
    t <- (read :: String -> Int) <$> getLine
    replicateM_ t $ do
        [a, b, k] <- (map (read :: String -> Int64) . words) <$> getLine
        printf "%lld\n" $ solve a b k

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

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

solve :: [Integer] -> Integer
solve [a, b, k]
    | even k    = (a - b) * c
    | otherwise = (a - b) * c + a
        where c = div k 2

main :: IO ()
main = do
    t <- readInt
    qs <- replicateM t $ readInts
    mapM_ print $ map solve $ map (map toInteger) qs

import Data.Int
import Control.Monad
main = do
  t <- readLn
  replicateM_ t $ do
    [a,b,k] <- map read . words <$> getLine
    print ((k+1) `div` 2 * a - k `div` 2 * b :: Int64)

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

onecase = do
		[a,b,k]<- map read <$> words <$> getLine ::IO [Integer]
		print $ (a-b)*(div k 2) + a *(mod k 2)

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

--ghc 7.10

finalPosition a b k = kOdd * a - kEven * b
    where
        kEven = k `div` 2
        kOdd = k - kEven

main = do
    nStr <- getLine
    contents <- getContents
    let qs = map (map read . words) . lines $ contents :: [[Integer]]
    sequence . map print . map (\[a,b,k] -> finalPosition a b k) $ qs

module Main where

import Control.Monad

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

getList :: IO [Integer]
getList = (map read) <$> words <$> getLine

solve :: [Integer] -> Integer
solve ins =
    let a = ins !! 0
        b = ins !! 1
        k = ins !! 2
        c = k `div` 2
    in ((-1) * b * c) + (k - c) * a

main :: IO ()
main = do
    t <- getInt
    replicateM_ t $ do ins <- getList
                       print $ solve ins

getFrogs :: Int -> IO [[Int]]
getFrogs 0 = do return []
getFrogs t = do
    line <- getLine
    let xs = map (\s -> read s :: Int) (words line)
    more <- getFrogs (t - 1)
    return (xs : more)

main = do
    line <- getLine
    let n = read line :: Int
    frogs <- getFrogs n
    mapM print (positions frogs)

positions :: [[Int]] -> [Int]
positions [] = []
positions ([right, left, steps] : frogs)
    = pos : (positions frogs)
      where pos = if even steps then total else total + right
            total = (right - left) * (steps `div` 2)

import Control.Monad
import Data.Bits

main = getLine
   >>= readQueries . read
   >>= putStrLn . calc

readQueries :: Int -> IO [String]
readQueries t = mapM (\_ -> getLine) [1..t]

calc :: [String] -> String
calc lines = foldr go "" lines
  where go line ans = show res ++ "\n" ++ ans
          where [s1, s2, s3] = words line
                a = read s1
                b = read s2
                k = read s3
                halfK = div k 2
                res = (.&.) k 1 + halfK * a - (b * halfK) :: Integer

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

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

solve :: [Int] -> Int
solve [a, b, k]
    | even k    = (a - b) * c
    | otherwise = (a * (c + 1)) - b * c
        where c = div k 2

main :: IO ()
main = do
    t <- readInt
    qs <- replicateM t $ readInts
    mapM_ print $ map solve qs

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

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

solve :: [Int] -> Int
solve [a, b, k]
    | even k    = (a - b) * c
    | otherwise = (a - b) * c + a
        where c = div k 2

main :: IO ()
main = do
    t <- readInt
    qs <- replicateM t $ readInts
    mapM_ print $ map solve qs

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

onecase = do
		[a,b,k]<- map read <$> words <$> getLine ::IO [Int]
		print $ (a-b)*(div k 2) + a *(mod k 2)

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

--ghc 7.10

finalPosition a b k = kOdd * a - kEven * b
    where
        kEven = k `div` 2
        kOdd = k - kEven

main = do
    nStr <- getLine
    contents <- getContents
    let qs = map (map read . words) . lines $ contents :: [[Int]]
    sequence . map print . map (\[a,b,k] -> finalPosition a b k) $ qs

--ghc 7.10

finalPosition :: (Integral a) => a -> a -> a -> a
finalPosition a b k = kOdd * a - kEven * b
    where
        kEven = k `div` 2
        kOdd = k - kEven

main = do
    nStr <- getLine
    contents <- getContents
    let qs = map (map read . words) . lines $ contents :: [[Int]]
    sequence . map print . map (\[a,b,k] -> finalPosition a b k) $ qs


{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Control.Applicative
import Data.Int
import Debug.Trace
import qualified Data.ByteString.Char8 as B

solve :: Int -> B.ByteString -> Int64
solve k s
    | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s
    | B.count '1' s < k = 0
    | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s
  where n = B.length s
        kth = (B.findIndices (== '1') s) !! (k-1)
        f (!a, (!j, !c)) d
            | d == '0' = (na, (j, c))
            | d == '1' = if j+c < n
                then (na, (j+c, 1 + zeros (j+c) s))
                else (na, (n, 0))
          where na = a + fromIntegral c

zeros :: Int -> B.ByteString -> Int
zeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)

l2 :: B.ByteString -> Int64
l2 s = (l * (l+1)) `div` 2
  where l = fromIntegral $ B.length s

main = do
    k <- read . B.unpack <$> B.getLine
    s <- head . B.words <$> B.getLine
--    [k', s] <- B.words <$> B.getContents
--    let k = read . B.unpack $ k'
    putStrLn . show $ solve k s

{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Control.Applicative
import Data.Int
import Debug.Trace
import qualified Data.ByteString.Char8 as B

solve :: Int -> B.ByteString -> Integer
solve k s
    | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s
    | B.count '1' s < k = 0
    | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s
  where n = B.length s
        kth = (B.findIndices (== '1') s) !! (k-1)
        f (!a, (!j, !c)) d
            | d == '0' = (na, (j, c))
            | d == '1' = if j+c < n
                then (na, (j+c, 1 + zeros (j+c) s))
                else (na, (n, 0))
          where na = a + fromIntegral c

zeros :: Int -> B.ByteString -> Int
zeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)

l2 :: B.ByteString -> Integer
l2 s = (l * (l+1)) `div` 2
  where l = fromIntegral $ B.length s

main = do
    [k', s] <- B.words <$> B.getContents
    let k = read . B.unpack $ k'
    putStrLn . show $ solve k s

{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Control.Applicative
import Data.Int
import Debug.Trace
import qualified Data.ByteString.Char8 as B

solve :: Int -> B.ByteString -> Int64
solve k s
    | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s
    | B.count '1' s < k = 0
    | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s
  where n = B.length s
        kth = (B.findIndices (== '1') s) !! (k-1)
        f (!a, (!j, !c)) d
            | d == '0' = (na, (j, c))
            | d == '1' = if j+c < n
                then (na, (j+c, 1 + zeros (j+c) s))
                else (na, (n, 0))
          where na = a + fromIntegral c

zeros :: Int -> B.ByteString -> Int
zeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)

l2 :: B.ByteString -> Int64
l2 s = (l * (l+1)) `div` 2
  where l = fromIntegral $ B.length s

main = do
    [k', s] <- B.words <$> B.getContents
    let k = read . B.unpack $ k'
    putStrLn . show $ solve k s

module Main where

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

import Data.Time.Calendar

main = interact (show . solve . lines)

solve :: [String] -> Integer
solve [sK, str] = answer where
    answer = case k of
        0 -> sum $ map (\x -> x * (x - 1) `div` 2) oneGroups
        _ -> sum $ zipWith (*) oneGroups (drop k oneGroups)
    oneGroups = map (fromIntegral . length) $ group sums :: [Integer]
    sums = elems sumArray

    sumArray = array allBounds [(i, sumArrayF i) | i <- range allBounds]
    allBounds = (0, snd $ bounds strArray)

    sumArrayF 0 = 0
    sumArrayF i = strArray ! i + sumArray ! (i - 1)

    strArray = listArray (1, length str) $ map ((\x -> x - ord '0') . ord) str
    k = read sK :: Int

import qualified Data.ByteString.Char8 as C
import IO
import Data.Maybe

main = print . solve =<< parse stdin
-- main = print . solve $ (215001, C.replicate (1000000) '1')

parse h = do
   input <- glines $ C.hGetContents h
   let k = readInt $ input !! 0
       s = input !! 1
   return (k, s)

solve :: (Int, C.ByteString) -> Integer
solve (k, s)
   | k == 0 = sum $ map g z
   | k /= 0 = sum $ zipWith f z (drop k z)
   where
      z     = map C.length . C.split '1' $ s
      f x y = (fromIntegral x + 1) * (fromIntegral y + 1)
      g x   = fromIntegral x * (fromIntegral x + 1) `div` 2

-- lib

glines = fmap (map (C.takeWhile (/='\r')) . C.lines)
readInt = fst . fromJust . C.readInt
readIntList = map readInt . C.words

-- vim: set expandtab:

import Control.Monad
import Data.List
encode :: String -> [Integer]
encode s = let (s1, s2) = span (== '0') s
           in if null s2 then [genericLength s1 + 1]
                         else genericLength s1 + 1: encode (tail s2)
main = do
  k <- (liftM read) getLine
  s <- getLine
  let l = encode s
  putStrLn . show . sum $ if k == 0 then map (\x -> div (x * (x-1)) 2) l
                                    else zipWith (*) l (drop k l)

split x xs = split' xs
	where
		split' xs = xs' : if null xs'' then [] else split' $ tail xs''
			where
				(xs', xs'') = break (== x) xs

solve k s
	| k == 0 = sum $ map (\c -> c*(c-1) `div` 2) cs
	| otherwise = sum $ zipWith (*) cs $ drop k cs
	where
		cs = map fromIntegral . map ((+ 1) . length) $ split '1' s

main = do
	k <- readLn
	s <- getLine
	print $ solve k s

{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Control.Applicative
import Data.Int
import Debug.Trace
import qualified Data.ByteString.Char8 as B

solve :: Int -> B.ByteString -> Int64
solve k s
    | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s
    | B.count '1' s < k = 0
    | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s
  where n = B.length s
        kth = (B.findIndices (== '1') s) !! (k-1)
        f (!a, (!j, !c)) d
            | d == '0' = (na, (j, c))
            | d == '1' = if j+c < n
                then (na, (j+c, 1 + zeros (j+c) s))
                else (na, (n, 0))
          where na = a + fromIntegral c

zeros :: Int -> B.ByteString -> Int
zeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)

l2 :: B.ByteString -> Int64
l2 s = let l = fromIntegral $ B.length s in (l * (l+1)) `div` 2

main = do
    [k', s] <- B.words <$> B.getContents
    let k = read . B.unpack $ k'
    putStrLn . show $ solve k s

main = interact $ show.solve.(\[x,y]->(read x,y)).lines

solve :: (Int,String) -> Integer
solve (0,cs) = sum.map (\n->(n*(n-1))`div`2)$ f cs
solve (k,cs) = sum.s (zipWith (*)) (drop k) $ f cs
   where s g h x = g x (h x)

f :: String -> [Integer]
f cs = case span ('0'==) cs of
         (xs,(y:ys)) -> (succ.fromIntegral.length $ xs):f ys
         (xs,[])     -> return.succ.fromIntegral.length $ xs

import Data.Int

split x xs = split' xs
	where
		split' xs = xs' : if null xs'' then [] else split' $ tail xs''
			where
				(xs', xs'') = break (== x) xs

solve k s
	| k == 0 = sum $ map (\c -> c*(c-1) `div` 2) cs
	| otherwise = sum $ zipWith (*) (drop k cs) cs
	where
		cs = map fromIntegral . map ((+ 1) . length) $ split '1' s

main = do
	k <- readLn
	s <- getLine
	print (solve k s)

split x xs = split' xs
	where
		split' xs = xs' : if null xs'' then [] else split' $ tail xs''
			where
				(xs', xs'') = break (== x) xs

solve k s
	| k == 0 = sum $ map (\c -> c*(c-1) `div` 2) cs
	| otherwise = sum $ zipWith (*) (drop k cs) cs
	where
		cs = map ((+ 1) . fromIntegral . length) $ split '1' s

main = do
	k <- readLn
	s <- getLine
	print $ solve k s

{- OPTIONS_GHC -O3 -fno-spec-constr-count -}
import Control.Monad
import Control.Applicative
import Data.Int
import Debug.Trace
import qualified Data.ByteString.Char8 as B

solve :: Int -> B.ByteString -> Integer
solve k s
    | k == 0 = sum . map l2 . filter ((=='0') . B.head) $ B.group s
    | B.count '1' s < k = 0
    | otherwise = fst $ B.foldl' f (0, (kth, 1 + zeros kth s)) s
  where n = B.length s
        kth = (B.findIndices (== '1') s) !! (k-1)
        f (a, (j, c)) d
            | d == '0' = (na, (j, c))
            | d == '1' = if j+c < n
                then (na, (j+c, 1 + zeros (j+c) s))
                else (na, (n, 0))
          where na = a + fromIntegral c

zeros :: Int -> B.ByteString -> Int
zeros i = B.length . B.takeWhile (== '0') . B.drop (i+1)

l2 :: B.ByteString -> Integer
l2 s = l * l
  where l = fromIntegral $ B.length s

main = do
    [k', s] <- B.words <$> B.getContents
    let k = read . B.unpack $ k'
    putStrLn . show $ solve k s

module Main where

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

import Data.Time.Calendar

main = interact (show . solve . lines)

solve :: [String] -> Int
solve [sK, str] = answer where
    answer = case k of
        0 -> sum $ map (\x -> x * (x - 1) `div` 2) oneGroups
        _ -> sum $ zipWith (*) oneGroups (drop k oneGroups)
    oneGroups = map length $ group sums
    sums = elems sumArray

    sumArray = array allBounds [(i, sumArrayF i) | i <- range allBounds]
    allBounds = (0, snd $ bounds strArray)

    sumArrayF 0 = 0
    sumArrayF i = strArray ! i + sumArray ! (i - 1)

    strArray = listArray (1, length str) $ map ((\x -> x - ord '0') . ord) str
    k = read sK :: Int

module Main where

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

import Data.Time.Calendar

main = interact (show . solve . lines)

solve :: [String] -> Int
solve [sK, str] = answer where
    answer = case k of
        0 -> length $ filter (=='0') str
        1 -> length $ filter (=='1') str
        _ -> sum $ zipWith (*) oneGroups (drop k oneGroups)
    oneGroups = map length $ group sums
    sums = elems sumArray

    sumArray = array allBounds [(i, sumArrayF i) | i <- range allBounds]
    allBounds = (0, snd $ bounds strArray)

    sumArrayF 0 = 0
    sumArrayF i = strArray ! i + sumArray ! (i - 1)

    strArray = listArray (1, length str) $ map ((\x -> x - ord '0') . ord) str
    k = read sK :: Int

module Main where

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

import Data.Time.Calendar

main = interact (show . solve . lines)

solve :: [String] -> Int
solve [sK, str] = answer where
    answer = case k of
        0 -> length $ filter (=='0') str
        _ -> sum $ zipWith (*) oneGroups (drop k oneGroups)
    oneGroups = map length $ group sums
    sums = elems sumArray

    sumArray = array allBounds [(i, sumArrayF i) | i <- range allBounds]
    allBounds = (0, snd $ bounds strArray)

    sumArrayF 0 = 0
    sumArrayF i = strArray ! i + sumArray ! (i - 1)

    strArray = listArray (1, length str) $ map ((\x -> x - ord '0') . ord) str
    k = read sK :: Int

import qualified Data.ByteString.Char8 as C
import IO
import Data.Maybe

main = print . solve =<< parse stdin
-- main = print . solve $ (215001, C.replicate (1000000) '1')

parse h = do
   input <- glines $ C.hGetContents h
   let k = readInt $ input !! 0
       s = input !! 1
   return (k, s)

solve (k, s)
   | k == 0 = sum $ map g z
   | k /= 0 = sum $ zipWith f z (drop k z)
   where
      z     = map C.length . C.split '1' $ s
      f x y = (x + 1) * (y + 1)
      g x   = x * (x + 1) `div` 2

-- lib

glines = fmap (map (C.takeWhile (/='\r')) . C.lines)
readInt = fst . fromJust . C.readInt
readIntList = map readInt . C.words

-- vim: set expandtab:

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe

main = print . solve =<< parse stdin

parse h = do
   input <- glines $ C.hGetContents h
   let k = readInt $ input !! 0
       s = input !! 1
   return (k, s)

solve (k, s) = sum $ zipWith f z (drop k z)
   where
      z = map C.length . C.split '1' $ s
      f x y = (x + 1) * (y + 1)

-- lib

glines = fmap (map (C.takeWhile (/='\r')) . C.lines)
readInt = fst . fromJust . C.readInt
readIntList = map readInt . C.words

-- vim: set expandtab:

import Control.Monad
import Data.List
encode s = let (s1, s2) = span (== '0') s
           in if null s2 then [length s1]
                         else length s1 : encode (tail s2)
main = do
  k <- (liftM read) getLine
  s <- getLine
  let l = encode s
      val = if k == 0 then sum $ map (\x -> div (x * (x+1)) 2) l
                      else sum $ zipWith (\x y -> (x+1) * (y+1)) l (drop k l)
  putStrLn $ show val

solve :: Int -> String -> Int
solve 0 _  =  0
solve n line  =  solve' ones (drop n ones) 0
  where
    ones  =  [0] ++ (map snd $ filter (('1' ==) . fst) (zip line [1..])) ++ [length line + 1]
    solve' :: [Int] -> [Int] -> Int -> Int
    solve' (l1:l2:ls) (r1:r2:rs) acc  =  acc' `seq` solve' (l2:ls) (r2:rs) acc'
      where
        acc'  =  acc + ((l2-l1)*(r2-r1))
    solve' _ _ acc  =  acc

main :: IO ()
main  =  do
    n <- readLn::IO Int
    line <- getLine
    print $ solve n line

import Data.List

main = interact $ show.solve.(\[x,y]->(read x,y)).lines

solve :: (Int,String) -> Int
solve (0,cs) = sum . map (h.length) . filter (('0'==).head) $ group cs
solve (k,cs) = let (xs1,xs2) = span ('0'==) cs
               in case f k ('1'==) xs2 of
                    Just ((y:ys),zs) -> let ws = takeWhile ('0'==) zs
                                        in (1+length xs1)*(1+length ws) + solve (k,ys++zs)
                    Nothing -> 0

f :: Int -> (a -> Bool) -> [a] -> Maybe ([a],[a])
f n p []
  | n==0      = Just ([],[])
  | otherwise = Nothing
f n p (x:xs)
  | n==0      = Just ([],x:xs)
  | p x       = f (n-1) p xs >>= g x
  | otherwise = f n p xs >>= g x

g :: a -> ([a],[a]) -> Maybe ([a],[a])
g x (xs,ys) = Just (x:xs,ys)

h n = (n*(n+1))`div`2

split x xs = split' xs
	where
		split' xs = xs' : if null xs'' then [] else split' $ tail xs''
			where
				(xs', xs'') = break (== x) xs

solve k s
	| k == 0 = sum $ map (\c -> c*(c-1) `div` 2) cs
	| otherwise = sum $ zipWith (*) (drop k cs) cs
	where
		cs = map ((+ 1) . length) $ split '1' s

main = do
	k <- readLn
	s <- getLine
	print $ solve k s


import Data.List

main = interact $ solver

solver str = unwords $ map show res where
             _:ws = words str
             vals = map read ws
             res = solve (reverse $ sort $ vals) []

solve :: [Int] -> [Int] -> [Int]
solve [] res = res
solve (h:t) res = solve remaining (h : res) where
                  to_remove = map (gcd h) res
                  to_remove2 = reverse $ sort $ concatMap (replicate 2) to_remove
                  remaining = exclude t to_remove2

exclude [] _ = []
exclude v [] = v
exclude (h1:t1) v2@(h2:t2)
    | h1 == h2 = exclude t1 t2
    | h1 > h2  = h1 : exclude t1 v2

{-# 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 (Map)
import qualified Data.Map as Map
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
  xs <- getInts

  let
    ms = Map.fromListWith (+) $ zip xs $ repeat 1

    f 0 _ r = r
    f n s r = f (n-1) s' (m:r)
      where
        m = fst $ Map.findMax s
        s' = foldl remove s $ m:(xs ++ xs)
          where
            xs = map (gcd m) r

            remove s x
              | c == 1 = x `Map.delete` s
              | otherwise = Map.adjust (\x -> x-1) x s
              where
                c = s Map.! x

  putStrLn $ unwords $ map show $ f n ms []

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

main = do
	(_ : xs) <- fmap (map read . words) getContents
	let m = Map.fromList $ fmap (\us@(u : _) -> (u, length us)) . group . sort $ xs
	foldl1 (>>) $ map (putStrLn . show) $ solve m []

solve m ans
	| Map.null m	= ans
	| otherwise		=
		let
			x		= fst $ Map.findMax m
			delList	= map (gcd x) ans
		in
			solve (foldl myDelete m (x : (delList ++ delList))) (x : ans)

myDelete m k = if (m ! k) == 1 then Map.delete k m else Map.adjust (subtract 1) k m

import Control.Monad
import Data.IntMap hiding (map)
import Prelude hiding (lookup,null)

build m [] = m
build m (x:xs) = if lookup x m == Nothing then build (insert x 1 m) xs else build (update (return . succ) x m) xs

main :: IO()
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words) getLine :: IO [Int]
    let m = build empty a
    mapM_ (\x -> putStr ((show x) ++ " ")) (solve m [])

solve m a
 |null m = a
 |otherwise = let x = getMax m
                  m' = deduct m (x:(map (gcd x) a))
              in solve m' (x:a)

getMax m = let Just ((k,_),_) = maxViewWithKey m in k

deduct m [] = m
deduct m (x:xs) = let v = lookup x m
                      nm = if v==Nothing then m else if v<=Just 2 then delete x m else adjust (\l -> l-2) x m
                  in deduct nm xs

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

main = do
	(_ : xs) <- fmap (map read . words) getContents
	let m = Map.fromList $ fmap (\us@(u : _) -> (u, length us)) . group . sort $ xs
	foldl1' (>>) $ map (putStrLn . show) $ solve m []

solve m ans
	| Map.null m	= ans
	| otherwise		=
		let
			x		= fst $ Map.findMax m
			delList	= map (gcd x) ans
		in
			solve (foldl' myDelete m (x : (delList ++ delList))) (x : ans)

myDelete m k = if (m ! k) == 1 then Map.delete k m else Map.adjust (subtract 1) k m

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

main = do
	(_ : xs) <- fmap (map read . words) getContents
	let m = Map.fromList $ fmap (\us@(u : _) -> (u, length us)) . group . sort $ xs
	foldl1' (>>) $ map (putStrLn . show) $ solve m []

solve m ans
	| Map.null m	= ans
	| otherwise		=
		let
			x		= fst $ Map.findMax m
			delList	= map (gcd x) ans
		in
			solve (foldl myDelete m (x : (delList ++ delList))) (x : ans)

myDelete m k = if (m ! k) == 1 then Map.delete k m else Map.adjust (subtract 1) k m

import Data.List

main = interact $ solver

solver str = unwords $ map show res where
             _:ws = words str
             vals = map read ws
             res = solve (reverse $ sort $ vals) []

solve :: [Int] -> [Int] -> [Int]
solve [] res = res
solve (h:t) res = solve remaining (h : res) where
                  to_remove = map (gcd h) res
                  to_remove2 = reverse $ sort $ to_remove
                  remaining = exclude t to_remove2

exclude [] _ = []
exclude v [] = v
exclude (h1:t1) v2@(h2:t2)
    | h1 == h2 = exclude (tail t1) t2
    | h1 > h2  = h1 : exclude t1 v2

import qualified Data.Map as Map
import Data.List as List

readInts str = map read (words str)

g ys m =
  if Map.null m then ys
  else  if k==0 then g ys (Map.delete y m)
  else g (y:ys) (Map.adjust (flip (-) 1) y m')
  where
    (y, k) = Map.findMax m
    gs = map (gcd y) ys
    m' = foldr (Map.adjust (flip (-) 2) ) m gs

main :: IO ()
main = do
 -- n <- fmap read getLine :: IO Int
  getLine
  xs <- fmap readInts getLine :: IO [Int]
  let xs' = List.group $ List.sort xs
  let m = Map.fromList $ map (\lst-> (head lst, length lst)) xs'
  putStr $ unwords $ map show (g [] m)

{-# OPTIONS_GHC -O2 -optc-O2 #-}
import Prelude hiding (getLine)
import Data.List (unfoldr)
import Control.Applicative ((<$>), (<*>))
import Data.ByteString (ByteString, getLine)
import qualified Data.ByteString.Char8 as B

import Data.Map (Map, empty, alter, findMax, deleteMax, adjust)
import qualified Data.Map as M

solve :: [Int] -> [Int]
solve xs = loop [] (foldr (alter inc) empty xs :: Map Int Int)
    where
    inc Nothing  = Just 1
    inc (Just i) = Just $ 1 + i
    go = adjust $ \i -> i - 2

    loop acc cnt
        | M.null cnt = acc
        | otherwise  = case findMax cnt of
            (_, 0) -> loop acc (deleteMax cnt)
            (k, _) -> loop (k:acc) . foldr go (adjust pred k cnt) $ map (gcd k) acc

parse :: ByteString -> [Int]
parse = unfoldr $ B.readInt . B.dropWhile (== ' ')

main :: IO ()
main = getLine >> getLine >>= putStrLn . unwords . map show . solve . parse

import Control.Monad
import Data.IntMap hiding (map)
import Prelude hiding (lookup,null)

build m [] = m
build m (x:xs) = if lookup x m == Nothing then build (insert x 1 m) xs else build (update (return . succ) x m) xs

main :: IO()
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words) getLine :: IO [Int]
    let m = build empty a
    print $ solve m []

solve m a
 |null m = a
 |otherwise = let x = getMax m
                  m' = deduct m (x:(map (gcd x) a))
              in solve m' (x:a)

getMax m = let Just ((k,_),_) = maxViewWithKey m in k

deduct m [] = m
deduct m (x:xs) = let v = lookup x m
                      nm = if v==Nothing then m else if v<=Just 2 then delete x m else adjust (\l -> l-2) x m
                  in deduct nm xs

import qualified Data.Map as Map
import Data.List as List

readInts str = map read (words str)

g ys m =
  if Map.null m then ys
  else  if k==0 then g ys (Map.delete y m)
  else g (y:ys) (Map.deleteMax m')
  where
    (y, k) = Map.findMax m
    gs = map (gcd y) (y:ys)
    m' = foldr (Map.adjust (flip (-) 2) ) m gs

main :: IO ()
main = do
 -- n <- fmap read getLine :: IO Int
  getLine
  xs <- fmap readInts getLine :: IO [Int]
  let xs' = List.group $ List.sort xs
  let m = Map.fromList $ map (\lst-> (head lst, length lst)) xs'
  putStr $ unwords $ map show (g [] m)


import Data.List

solve :: [Int] -> String
solve [] = "Yes"
solve [x] = "Yes"
solve (a:xs@(b:_)) = if a==b then "No" else solve xs

testCase = do
    n <- getLine
    numList <- words `fmap` getLine
    let nums = read `map` numList :: [Int]
    putStrLn $ solve (sort nums)

repeatN 0 m = return []

repeatN n m = do
  x1 <- m
  x2 <- repeatN (n - 1) m
  return (x1 : x2)

main = do
    n <- read `fmap` getLine :: IO Int
    repeatN n testCase

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

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

main = do
  n <- readLn :: IO Int
  forM_
    [1 .. n]
    ( \_ -> do
        _ <- readLn :: IO Int
        arr <- readInts
        putStrLn $
          if (length . nub) arr == length arr
            then "YES"
            else "NO"
    )

import Data.List

solve :: [Int] -> String
solve [] = "Yes"
solve [x] = "Yes"
solve (a:b:xs) = if a==b then "No" else solve xs

testCase = do
    n <- getLine
    numList <- words `fmap` getLine
    let nums = read `map` numList :: [Int]
    putStrLn $ solve (sort nums)

repeatN 0 m = return []

repeatN n m = do
  x1 <- m
  x2 <- repeatN (n - 1) m
  return (x1 : x2)

main = do
    n <- read `fmap` getLine :: IO Int
    repeatN n testCase

solve :: [Int] -> String
solve [] = "Yes"
solve [x] = "Yes"
solve (a:b:xs) = if a==b then "No" else solve xs

testCase = do
    n <- getLine
    numList <- words `fmap` getLine
    let nums = read `map` numList :: [Int]
    putStrLn $ solve nums

repeatN 0 m = return []

repeatN n m = do
  x1 <- m
  x2 <- repeatN (n - 1) m
  return (x1 : x2)

main = do
    n <- read `fmap` getLine :: IO Int
    repeatN n testCase


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

main = do
	n <- fmap read getLine
	a <- replicateM n getLine
	b <- getLine
	putStrLn $ gao n a b

gao n a b = unlines $ sort $ concat $ d : e where
	m = sum (map length a) * 2 `div` n
	c = fmap sort $ accumArray (flip (:)) [] (1, m) $ map (\i -> (length i, i)) a
	d = if odd m then [] else f $ c!(div m 2)
	e = [zipWith (\i j -> min (i ++ b ++ j) (j ++ b ++ i)) (c!i) (c!(m - i))| i <- [1 .. div (m - 1) 2]]
	f [] = []
	f (x:y:z) = (x ++ b ++ y) : f z

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort, unfoldr)

main :: IO ()
main = do
   n <- read <$> getLine :: IO Int
   branches <- replicateM n getLine
   d <- getLine
   let lengths = map length branches
   let size = (2 * sum lengths) `div` n
   let branches' = map init . sort . map ( ++ d) $ branches
   mapM_ putStrLn $ solve size d branches'

solve :: Int -> String -> [String] -> [String]
solve sz d branches = unfoldr cN branches
  where cN :: [String] -> Maybe (String, [String])
        cN ([]) = Nothing
        cN bs = Just (start ++ d ++ smC, leOv)
           where start = head bs
                 fSz = sz - length start
                 (p1, smC:p2) = break ((== fSz).length) (tail bs)
                 leOv = p1 ++ p2

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)

main :: IO ()
main = do
   n <- read <$> getLine :: IO Int
   branches <- replicateM n getLine
   d <- getLine
   let lengths = map length branches
   let size = (2 * sum lengths) `div` n
   let branches' = (map init) . sort . (map ( ++ d)) $ branches
   mapM_ putStrLn $ solve size d branches'

solve :: Int -> String -> [String] -> [String]
solve _ _ ([]) = []
solve sz d branches = (start ++ d ++ smC):(solve sz d leOv)
  where start = head branches
        fSz = sz - length start
        (p1, (smC:p2)) = break ((== fSz).length) (tail branches)
        leOv = p1 ++ p2

module Main where

import Control.Monad
import Data.Ord
import Data.Monoid
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.List

strCmp sep (a:as) (b:bs) = case compare a b of
    EQ -> strCmp sep as bs
    res -> res
strCmp sep [] (b:_) = compare sep b
strCmp sep (a:_) [] = compare a sep
strCmp sep _ _ = EQ

newtype Prefix = Prefix (Char, [Char]) deriving Eq
instance Ord Prefix where
    compare (Prefix (sep, a)) (Prefix (_, b)) = strCmp sep a b

main = do
    n <- read `liftM` getLine
    names <- replicateM n getLine
    sep <- head `liftM` getLine

    let prefixSet = Set.fromList $ map (\s -> Prefix (sep, s)) names
        postfixMap = Map.fromList $                                                                                map (\s -> (length (Set.findMin s), s)) $
            map Set.fromList $
            groupBy (\a b -> length a == length b) $
            sortBy (comparing length) names
        totalLen = sum $ map length names
        rowLen = totalLen `div` (n `div` 2) + 1
        (res, _, _) = until
            (\(_, set, _) -> Set.null set)
            (\(res, prefixSet, postfixMap) ->
                    let (Prefix (_, prefix), prefixSet') = Set.deleteFindMin prefixSet
                        prefixLen = length prefix
                        postfixLen = rowLen - 1 - prefixLen

                        postfixMap' = Map.insertWith' ( \_ entry -> Set.delete prefix entry ) prefixLen undefined postfixMap
                        (postfix, postfixSet'') = Set.deleteFindMin $ postfixMap' Map.! postfixLen
                        postfixMap'' = Map.insert postfixLen postfixSet'' postfixMap'

                        prefixSet'' = Set.delete (Prefix (sep, postfix)) prefixSet'
                    in ( ( prefix ++ [sep] ++ postfix ) : res, prefixSet'', postfixMap'' )
                )
            ([], prefixSet, postfixMap)

    --putStrLn $ show postfixMap
    putStr $ unlines $ reverse res

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

main = do
  n <- fmap read getLine
  a <- replicateM n getLine
  b <- getLine
  putStr $ gao n a b

gao :: Int -> [String] -> String -> String
gao n a b =
  unlines $ sort $ concat $ d : e
  where
    m = sum (map length a) * 2 `div` n
    c = fmap sort $ accumArray (flip (:)) [] (1, m) [(length i, i) | i <- a]
    --should use fmap
    --in this case fmap is for functor (Array Int)
    --not map
    --map is for [] functor, for [] functor fmap = map
    d = if odd m then [] else f $ c!(div m 2)
    e = [zipWith (\x y -> min (x ++ b ++ y) (y ++ b ++ x)) (c!i) (c!(m - i)) | i <- [1..div (m - 1) 2]]
    f [] = []
    f (x:y:z) = (x ++ b ++ y) : f z

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

main = do
	n <- fmap read getLine
	c <- replicateM n getLine
	d <- getLine
	putStrLn $ gao n c d

gao n a b = unlines $ sort $ concat $ d : e where
	m = sum (map length a) * 2 `div` n
	c = fmap sort $ accumArray (flip (:)) [] (1, m) $ map (\i -> (length i, i)) a
	d = if odd m then [] else f $ c!(div m 2)
	e = [zipWith (\i j -> min (i ++ b ++ j) (j ++ b ++ i)) (c!i) (c!(m - i))| i <- [1 .. div (m - 1) 2]]
	f [] = []
	f (x:y:z) = (x ++ b ++ y) : f z

import Data.List
import Data.Maybe

linesBuild _ [] = []
linesBuild c@(delimiter, minLength, maxLength) cs@(csh:cst) =
	let {(cs1, cs2h:cs2t) = splitAt (fromJust $
		findIndex (\x -> length x == minLength + maxLength - length csh)
			cst) cst} in
	(csh ++ [delimiter] ++ cs2h): linesBuild c (cs1 ++ cs2t)

main = do { ns <- getLine
	; let n = read ns
	; cities <- mapM (\_ -> getLine) [1..n]
	; delimiter <- getLine >>= (return . head)
	; let (minLength, maxLength) = let (l:lens) = sort $ map length cities in
		(l, head $ reverse lens)
	; mapM_ (\x -> putStr (x ++ "\n"))
		$ linesBuild (delimiter, minLength, maxLength) (sortBy
		(\a b -> compare (a++[delimiter]) (b++[delimiter])) cities)
}

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

main = do
	n <- fmap read getLine
	a <- replicateM n getLine
	b <- getLine
	putStrLn $ gao n a b

gao n a b = unlines $ sort $ concat $ d : e where
	m = sum (map length a) * 2 `div` n
	c = accumArray (flip (:)) [] (1, m) $ map (\i -> (length i, i)) a
	d = if odd m then [] else f $ c!(div m 2)
	e = [zipWith (\i j -> min (i ++ b ++ j) (j ++ b ++ i)) (c!i) (c!(m - i))| i <- [1 .. div (m - 1) 2]]
	f [] = []
	f (x:y:z) = (x ++ b ++ y) : f z

import Control.Monad
import Data.Ord
import Data.Monoid
import qualified Data.Set as Set

strCmp sep (a:as) (b:bs) = case compare a b of
    EQ -> strCmp sep as bs
    res -> res
strCmp sep [] (b:_) = compare sep b
strCmp sep (a:_) [] = compare a sep
strCmp sep _ _ = EQ

newtype Prefix = Prefix (Char, [Char]) deriving Eq
instance Ord Prefix where
    compare (Prefix (sep, a)) (Prefix (_, b)) = strCmp sep a b

main = do
    n <- read `liftM` getLine
    names <- replicateM n getLine
    sep <- head `liftM` getLine

    let prefixSet = Set.fromList $ map (\s -> Prefix (sep, s)) names
        postfixSet = Set.fromList names
        (res, _, _) = until
            (\(_, set, _) -> Set.null set)
            (\(res, prefixSet, postfixSet) ->
                    let (Prefix (_, prefix), prefixSet') = Set.deleteFindMin prefixSet
                        (postfix, postfixSet') = Set.deleteFindMin $ Set.delete prefix postfixSet
                        prefixSet'' = Set.delete (Prefix (sep, postfix)) prefixSet'
                    in ( ( prefix ++ [sep] ++ postfix ) : res, prefixSet'', postfixSet' )
                )
            ([], prefixSet, postfixSet)

    putStr $ unlines $ reverse res

import Data.List
import Data.Maybe

linesBuild _ [] = []
linesBuild c@(delimiter, minLength, maxLength) cs@(csh:cst) =
	let {(cs1, cs2h:cs2t) = splitAt (fromJust $
		findIndex (\x -> length x == minLength + maxLength - length csh)
			cst) cst} in
	(csh ++ [delimiter] ++ cs2h): linesBuild c (cs1 ++ cs2t)

main = do { ns <- getLine
	; let n = read ns
	; cities <- mapM (\_ -> getLine) [1..n]
	; delimiter <- getLine >>= (return . head)
	; let (minLength, maxLength) = let (l:lens) = sort $ map length cities in
		(l, head $ reverse lens)
	; mapM_ (\x -> putStr (x ++ "\n"))
		$ linesBuild (delimiter, minLength, maxLength) (sort cities)
}

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)

main :: IO ()
main = do
   n <- read <$> getLine :: IO Int
   branches <- sort <$> replicateM n getLine :: IO [String]
   d <- getLine
   let lengths = map length branches
   let size = (2 * sum lengths) `div` n
   mapM_ putStrLn $ solve size d branches

solve :: Int -> String -> [String] -> [String]
solve _ _ ([]) = []
solve sz d branches = (start ++ d ++ smC):(solve sz d leOv)
  where start = head branches
        fSz = sz - length start
        (p1, (smC:p2)) = break ((== fSz).length) (tail branches)
        leOv = p1 ++ p2


{-
import HUnit

testNotVectors :: Test
testNotVectors  =  Test "TestNotVectors" $
    assertEq 0 (solve (0,0) (0,0) [])

testOneVector :: Test
testOneVector  =  TestList "TestOneVector"
    [Test "1" $ assertEq 5 (solve (6,16) (1,1) [(1,1)]),
     Test "2" $ assertEq 2 (solve (6,16) (1,1) [(2,2)]),
     Test "3" $ assertEq 0 (solve (4,1) (1,1) [(1,1)])]

testOneVectorWithZeroCoordinate :: Test
testOneVectorWithZeroCoordinate  =  TestList "TestOneVectorWithZeroCoordinate"
    [Test "1" $ assertEq 3 (solve (4,1) (1,1) [(1,0)]),
     Test "2" $ assertEq 2 (solve (4,4) (2,2) [(0,1)])]

testOneVectorWithNegativeCoordinate :: Test
testOneVectorWithNegativeCoordinate  =  TestList "TestOneVectorWithNegativeCoordinate"
    [Test "1" $ assertEq 1 (solve (6,6) (2,2) [(-1,-1)]),
     Test "2" $ assertEq 2 (solve (6,6) (5,3) [(-1,-1)]),
     Test "3" $ assertEq 1 (solve (6,6) (5,3) [(-1,-2)])]

testManyVectors :: Test
testManyVectors  =  Test "TestManyVectors" $
    assertEq 7 (solve (3,4) (1,1) [(2,0),(0,1),(-1,0),(0,-3),(-1,0),(0,-1),(-1,-1),(3,0),(0,4)])

testInput :: Test
testInput  =  TestList "TestInput"
    [Test "1" $ assertEq 4 (solve (4,5) (1,1) [(1,1),(1,1),(0,-2)]),
     Test "2" $ assertEq 0 (solve (10,10) (1,2) [(-1,0)])]

testBig :: Test
testBig  =  Test "TestBig" $
    assertEq (10^9 * 1000) (solve (10^9 + 1, 10^9 + 1) (1,1) (take 1000 (cycle [(1,1), (-1,-1)])))

test :: IO ()
test  =  mapM_ run
    [testNotVectors,
     testOneVector,
     testOneVectorWithZeroCoordinate,
     testOneVectorWithNegativeCoordinate,
     testManyVectors,
     testInput,
     testBig]

--------------------------------------------------------------------------------
-}

reads :: Read a => IO [a]
reads = getLine >>= sequence . map readIO . words

readVector :: IO (Integer, Integer)
readVector  =  do
  [x, y]  <-  Main.reads
  return (x, y)

solve :: (Integer, Integer) -> (Integer, Integer) -> [(Integer, Integer)] -> Integer
solve (n,m) (x,y) vs  =  snd (foldl solve' ((x,y), 0) vs)
  where
    solve' :: ((Integer, Integer), Integer) -> (Integer, Integer) -> ((Integer, Integer), Integer)
    solve' ((xc,yc), s) (x,y)  =  ((xc + x * res, yc + y * res), s + res)
      where
        x'  =  if x < 0 then div (xc-1) (-x) else div (n-xc) x
        y'  =  if y < 0 then div (yc-1) (-y) else div (m-yc) y
        res  =  case (x,y) of
          (0, 0) ->  error "Solve: Empty vector!"
          (0, y) -> y'
          (x, 0) -> x'
          (x, y) -> min x' y'

main :: IO ()
main  =  do
    [n, m]  <-  Main.reads
    [xc, yc]  <-  Main.reads
    k  <-  readLn
    vs <- mapM (const readVector) [1..k]
    print $ solve (n,m) (xc,yc) vs

import Data.List

solve ([n, m]:position:_:vectors) = head $ foldl' applyVector (0:position) vectors
  where applyVector [ans, x, y] [dx, dy] =
          let a = steps x n dx
              b = steps y m dy
              c = min a b
          in [ans + c, x + c * dx, y + c * dy]

        steps a q da
          | da > 0    = (q - a) `div` da
          | da < 0    = (a - 1) `div` (abs da)
          | otherwise = 10 ^ 9 + 1

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

import Control.Arrow
import Control.Monad
main = do
  [n,m] <- liftM (map read . words) getLine
  [xc,yc] <- liftM (map read . words) getLine
  k <- readLn
  vs <- replicateM k $ liftM (((!!0) &&& (!!1)) . map read . words) getLine
  print $ solve n m xc yc vs 0
solve _ _ _ _ [] a = a
solve n m x y ((vx,vy):vs) a  = solve n m (x + c*vx) (y + c*vy) vs $! a + c
    where nx = if vx > 0 then (n - x) `div` vx else (1 - x) `div` vx
          ny = if vy > 0 then (m - y) `div` vy else (1 - y) `div` vy
          c = if vx == 0 then ny else if vy == 0 then nx else min nx ny

import Data.ByteString.Char8(ByteString)
import qualified Data.ByteString.Char8 as B
import Data.List
import Control.Applicative

main = do
  [n,m] <- map read' . B.words <$> B.getLine
  [xc,yc] <- map read' . B.words <$> B.getLine
  _ <- getLine
  xys <- map ((\ [x,y] -> (x,y)) . map read' . B.words) . B.lines <$> B.getContents
  print $ solve [n,m] $ (xc,yc):xys

read' s = let Just (n,_) = B.readInt s in toInteger n

solve :: [Integer] -> [(Integer,Integer)] -> Integer
solve [n,m] (xy:xys) = fst $ foldl' (f [n,m]) (0,xy) xys

f [n,m] (i,(x,y)) (dx,dy)
  | dx == 0 = let k = if dy>0 then div (m-y) dy else div (1-y) dy
                    in (i+k,(x,y+k*dy))
  | dy == 0 = let k = if dx>0 then div (n-x) dx else div (1-x) dx
                    in (i+k,(x+k*dx,y))
  | otherwise = let kx = if dx>0 then div (n-x) dx else div (1-x) dx
                    ky = if dy>0 then div (m-y) dy else div (1-y) dy
                    k = min kx ky
                      in (i+k,(x+k*dx,y+k*dy))

import Data.List

bounds :: Integer->Integer->Integer->Integer
bounds n c dc
	| dc == 0 = 1000000001
	| dc < 0 = (1-c)`div`dc
	| otherwise = (n-c)`div`dc

travel n m  = go where
	go _ _ [] = 0
	go x y ([dx,dy]:t) = steps + go (x+steps*dx) (y+steps*dy) t
		where steps = min (bounds n x dx) (bounds m y dy)

result ([n,m]:[x,y]:_:v) = travel n m x y v

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

import Control.Monad

type Point = (Int, Int)

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

solve :: [Point] -> Point -> Point -> Integer
solve points start (n, m) = loop points start 0
    where loop :: [Point] -> Point -> Integer -> Integer
          loop [] _ acc = acc
          loop ((vx, vy):vs) (x, y) acc =
              loop vs (x + st * vx, y + st * vy) (acc + (toInteger st))
              where st = min (step x vx n) (step y vy m)
                    step a va k
                        | va == 0 = 10^10 -- aka infty
                        | va > 0  = (k - a) `div` va
                        | va < 0  = (1 - a)`div` va

main = do
  (n, m) <- (getLine >>= return . l2t . map (read::String->Int) . words)
  (x, y) <- (getLine >>= return . l2t . map (read::String->Int) . words)
  [k] <- (getLine >>= return . map (read::String->Int) . words)
  points <- forM [1..k] (\_ -> getLine >>= (return . l2t . map (read::String->Int). words))
  print $ solve points (x, y) (n, m)


main = interact (ans)
ans theInput = output $ answer $ intersect schedule where
	inputs = map (map (read::String->Int))(map words $ lines theInput)
	[n] = head inputs
	schedule = zip [1..n] [(l,r)|[l,r]<-take n $ tail inputs]
	intersect [_] = []
	intersect ((i,(a,b)):xs) = [(i,j)|(j,(c,d))<-xs,(a<=c && c<b)||(c<=a && a<d)] ++ intersect xs
	answer [] = [1..n]
	answer ((i,j):xs) = [k|k<-[i,j],elem k $ answer xs]
	output x = unlines $ map unwords $ map (map show) [[length x],x]

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Ord
import Text.Printf

main :: IO ()
main = do
  n <- readLn
  temp <- replicateM n $ sort . map read . words <$> getLine :: IO [[Int]]
  let groups =  sortBy (comparing  snd) $ zip [1.. ] temp
      answers = sort . map fst . (`mapMaybe` groups) $ \g -> do
        let groups' = filter (/= g) groups
            check (_, _ : end : _) (_, start : _) = end <= start
        if and $ zipWith check groups' (tail groups')
          then Just g
          else Nothing
  print $ length answers
  putStrLn . intercalate " " $ map show answers

import Data.List(find,sort)
main = do
  (_:input) <- fmap lines getContents
  let a :: [(Int,(Int,Int))]
      a = zip [1..] $ map parse input
      parse s = (l,r)
        where [l,r] = map read . words $ s
      n = length a
      ans = case find intersecting [(g,h) | g <- a, h <- a, fst g < fst h] of
              Nothing -> [1..n]
              Just ((i,(lx,rx)),(j,(ly,ry))) -> sort . filter good $ [i,j]

      intersecting ((_,(lx,rx)),(_,(ly,ry))) =
        rx > ly && lx < ry

      good idx = Nothing == find intersecting [(g,h) | g <- a, h <- a, fst g < fst h, fst g /= idx, fst h /= idx]

  print (length ans)
  putStrLn . unwords . map show $ ans

import Control.Monad (liftM, replicateM)
import Data.Array ((!), listArray, accumArray, elems)
import Data.List (intercalate)
import Prelude hiding (reads)

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

prints :: Show a => [a] -> IO ()
prints xs  =  print (length xs) >> prints' xs
  where
    prints'  =  putStrLn . intercalate " " . map show

solve :: Int -> [[Int]] -> [Int]
solve n groups  =  [i | i <- [1..n], countEdges == countEdge ! i]
  where
    groupsArray  =  listArray (1, n) groups
    countEdge  =  accumArray (+) 0 (1, n)
        [(i, length (edges i)) | i <- [1..n]]
    countEdges  =  div (sum (elems countEdge)) 2
    edges i  =  filter (intersect i) [1..n]
    intersect i j
      | i == j  =  False
      | otherwise
          =  l2 <= l1 && l1 < r2
          || l2 < r1 && r1 <= r2
          || l1 <= l2 && l2 < r1
          || l1 < r2 && r2 <= r1
      where
        [l1, r1]  =  groupsArray ! i
        [l2, r2]  =  groupsArray ! j

main :: IO ()
main  =  do
    n  <-  readLn
    groups  <-  replicateM n reads :: IO [[Int]]
    prints $ solve n groups

reads :: Read a => IO [a]
reads = getLine >>= sequence . map readIO . words

solve :: [Int] -> [(Int, Int, Int)]
solve xs  =  [(i, j, k) | i <- [1..n], j <- [1..n], k <- [1..n],
    i /= j, i /= k, j /= k,
    xs !! (i-1) == xs !! (j-1) + xs !! (k-1)]
  where
    n  =  length xs

printAns :: [(Int, Int, Int)] -> IO ()
printAns []  =  print (-1)
printAns ((i, j, k):xs)  =  putStrLn $ concat [show i, " ", show j, " ", show k]

main :: IO ()
main  =  getLine >> Main.reads >>= printAns . solve


findN::Int->Int
findN n | n<4 = 4 - n
findN n | (mod n 2) == 0 = 0
findN n = 1

inputN::Int->IO [Int]
inputN 0 = return []
inputN n = do
  z <- read <$> getLine
  (z:) <$> (inputN (n-1))

main::IO()
main = do
  n <- read <$> getLine
  lst <- inputN n
  mapM_ (print . findN) lst

f 2 = 2
f a = a `mod` 2

main = do
     x <- getLine
     y <- getContents
     mapM_ (putStrLn.show.f.read) $ lines y

f x
   | x == 2 = 2
   | otherwise = if odd x then 1 else 0

main = interact $ unlines . map ( show . f .  (read :: String -> Int) ) . tail . lines

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

solve :: Int -> Int
solve n = max (4 - n) (n `mod` 2)

import Control.Monad

main = do
  q <- read <$> getLine
  forM [1..q] $ \_ -> do
    n <- read <$> getLine
    print $ missing n

missing :: Int -> Int
missing 2 = 2
missing n
  | n `mod` 2 == 0 = 0
  | otherwise      = 1

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

process aa = print $ if aa==2 then 2 else if even aa then 0 else 1

main::IO ()
main=do
	s<- read <$> getLine:: IO Int
	a<- map read <$> replicateM s getLine ::IO [Int]
	mapM_ process a

--ghc 7.10

minMatches :: Int -> Int
minMatches n
    | n < 4 = 4 - n
    | otherwise = n `mod` 2

assembleCME :: [Int] -> [Int]
assembleCME = map minMatches

main = do
    qStr <- getLine
    contents <- getContents
    let ns = map read . words $ contents :: [Int]
    sequence . map print . assembleCME $ ns

main = interact $ unlines . map (show . solve . read) . tail . lines
solve n | n < 4 = 4 - n
        | odd n = 1
        | even n = 0


import Control.Monad

solve :: Int-> Int -> Int -> Bool
solve r b k = (n+1)<k
  where
    (x,y) = (max r b,min r b)
    g = gcd x y
    (x',y') = (x `div` g,y `div` g)
    n = (x'-2) `div` y'

routine :: IO ()
routine = do
  l <- fmap (map read . words) getLine
  if solve (head l) (l!!1) (l!!2) then putStrLn "OBEY" else putStrLn "REBEL"

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

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = fmap words getLine

getIntList :: IO [Integer]
getIntList = fmap (map read) getStrList

f :: Integer -> Integer -> Integer -> String
f a b k
    | r == 0 = if k < d then "REBEL" else "OBEY"
    | otherwise = if k <= div (b - 2) a + 1 then "REBEL" else "OBEY"
    where r = mod b a
          d = div b a
          l = lcm a b

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [r, b, k] <- getIntList
        let x = div r (gcd r b)
            y = div b (gcd r b) in
                putStrLn $ f (min x y) (max x y) k

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = fmap words getLine

getIntList :: IO [Integer]
getIntList = fmap (map read) getStrList

f :: Integer -> Integer -> Integer -> String
f r b k
    | k <= div b r = "REBEL"
    | otherwise = "OBEY"

main :: IO()
main = do
    t <- readLn
    replicateM_ t $ do
        [r, b, k] <- getIntList
        putStrLn $ f (min r b) (max r b) k

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = fmap words getLine

getIntList :: IO [Integer]
getIntList = fmap (map read) getStrList

upd :: Integer -> Integer -> Integer
upd u d
    | mod u d == 0 = div u d
    | otherwise = div u d + 1

f :: Integer -> Integer -> Integer -> String
f r b k
    | k < upd b r = "REBEL"
    | otherwise = "OBEY"

main :: IO()
main = do
    t <- readLn
    replicateM_ t $ do
        [r, b, k] <- getIntList
        putStrLn $ f (min r b) (max r b) k

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = fmap words getLine

getIntList :: IO [Integer]
getIntList = fmap (map read) getStrList

f :: Integer -> Integer -> Integer -> String
f a b k
    | r == 0 = if k < d then "REBEL" else "OBEY"
    | otherwise = if k <= div (b - 2) a + 1 then "REBEL" else "OBEY"
    where r = mod b a
          d = div b a

main :: IO()
main = do
    t <- readLn
    replicateM_ t $ do
        [r, b, k] <- getIntList
        putStrLn $ f (min r b) (max r b) k

import Control.Monad

solve :: Int-> Int -> Int -> Bool
solve r b k = n<k
  where
    (x,y) = (max r b,min r b)
    g = gcd x y
    (x',y') = (x `div` g,y `div` g)
    n = (x'-2) `div` y'

routine :: IO ()
routine = do
  l <- fmap (map read . words) getLine
  if solve (head l) (l!!1) (l!!2) then putStrLn "OBEY" else putStrLn "REBEL"

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

import Control.Monad

solve :: Int-> Int -> Int -> Bool
solve r b k = n<k
  where
    (x,y) = (max r b,min r b)
    g = gcd x y
    (x',y') = (x `div` g,y `div` g)
    n = (x'-1) `div` y'

routine :: IO ()
routine = do
  l <- fmap (map read . words) getLine
  if solve (head l) (l!!1) (l!!2) then putStrLn "OBEY" else putStrLn "REBEL"

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