import Control.Monad

type Ints = (Integer, Integer)
type Prices = (Integer, Integer)

data Test = Test (Ints, Ints) deriving (Show)

getData :: Int -> IO [Test]
getData t = replicateM t readTest

readTest :: IO Test
readTest = do
    first <- getLine
    second <- getLine
    let [x, y] = map read (words first)
    let [a, b] = map read (words second)
    return (Test ((x, y), (a, b)))

getAnswer :: [Test] -> [Integer]
getAnswer [] = []
getAnswer (first:rest) = [quantify first] ++ getAnswer rest

quantify :: Test -> Integer
quantify (Test ((x, y), (a, b))) = minimum [less*b + (greater - less)*a, (x + y)*a]
    where less = min x y
          greater = max x y

toIntList :: [Integer] -> [Integer]
toIntList list = list

main :: IO ()
main = do
    t <- getLine
    tests <- getData $ read t
    mapM_ print (getAnswer tests)

import Control.Monad

main = readLn >>= flip replicateM_ test

test = do
    (x:y:_) <- map (abs . read) . words <$> getLine
    (a:b:_) <- map read . words <$> getLine
    print $ min (a * (x + y)) (b * min x y + a * (max x y - min x y))

import qualified Data.List as L

dist_to_zero a b
  | a > b = dist_to_zero b a
  | a <= 0 && 0 <= b = 0
  | 0 <= a = a
  | b <= 0 = b

solve :: [Integer] -> Integer
solve [x,y,a,b] = d2 * (min b (2*a)) + d1 * a
  where d1 = abs (x-y)
        d2 = dist_to_zero x y
solve x = undefined

lines_to_pairs [] = []
lines_to_pairs (x:y:zz) = (unwords [x,y]):(lines_to_pairs zz)

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

import Control.Monad

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

routine :: IO ()
routine = do
  [x,y] <- (map read.words) <$> getLine
  [a,b] <- (map read.words) <$> getLine
  print $ if 2*a <= b then a*(x+y) else (min x y)*b + (abs (x - y))*a

import Control.Monad

main :: IO ()
main = do
  tt <- read <$> getLine
  replicateM_ tt $ do
    [x, y] <- (map read . words) <$> getLine
    [a, b] <- (map read . words) <$> getLine
    let f t = a * abs (t + x) + a * abs (t + y) + b * abs t
    putStrLn $ show $ minimum [f (-x), f (-y), f 0 :: Integer]

solve :: [Integer] -> Integer
solve (0:0:_) = 0
solve (0:y:a:b:_) = a*y
solve (x:0:a:b:_) = a*x
solve (x:y:a:b:_)
    | b > 2*a =  x*a + y*a
    | b <= 2*a = (min x y)*b + (abs (x - y))*a

test :: (Int) -> IO()
test 0 = return()
test x = do
    l1 <- getLine
    l2 <- getLine
    let t = l1 ++ " " ++ l2
    let arr = map (\a -> read a :: Integer ) $ words t
    let ans = solve arr
    let out = show ans
    putStrLn out
    test (x - 1)

main = do
    t <- getLine
    let x = read t :: Int

    test x

solve1 :: Integer -> Integer -> Integer -> Integer -> Integer
solve1 x y a b
    | b > 2*a           = a * (x +y)
    | otherwise         = b * mn + a * (mx - mn)
    where
        mn = min x y
        mx = max x y

solveTestCases :: Integer -> IO ()
solveTestCases 0 = return ()
solveTestCases n = do
    xy <- getLine
    ab <- getLine
    let
        (x:y:_) = map read $ words xy
        (a:b:_) = map read $ words ab
    print $ solve1 x y a b
    solveTestCases (n-1)

main :: IO ()
main = do
    t <- getLine
    solveTestCases (read t)

module Main where

import Control.Monad
import Data.List
import qualified Data.Set as S

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Integer]
getIntList = map read <$> getStrList

printStrList :: [String] -> IO ()
printStrList = putStrLn . intercalate " "

printList :: (Show a) => [a] -> IO ()
printList = printStrList . map show

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

(-->) :: a -> (a -> b) -> b
(-->) = flip ($)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, y] <- getIntList
        [a, b] <- getIntList
        print $ f x y a b

f :: Integer -> Integer -> Integer -> Integer -> Integer
f x y a b = minimum [(abs x + abs y) * a
                    ,abs (x - y) * a + min (abs x * b) (abs y * b)]

import           Data.List                      ( unfoldr )

-- https://stackoverflow.com/a/12882583/61394
chunks n = takeWhile (not . null) . unfoldr (Just . splitAt n)

f :: Integer -> Integer -> Integer -> Integer -> Integer

-- Rearrange so x' has the smaller absolute value.
f x y a b | x == 0 && y == 0 = 0
          | x == 0           = a * abs y
          | x < 0 && y < 0   = f (-x) (-y) a b
          | abs x > abs y    = f y x a b
          | x > 0 && y > 0   = x * min b (2 * a) + f 0 (y - x) a b
          | otherwise        = a * (abs x + abs y)

main =
  interact
    $ unlines
    . map (show . \(x : y : a : b : _) -> f x y a b)
    . chunks 4
    . tail
    . map read
    . words

import qualified Data.List as L

dist_to_zero a b
  | a > b = dist_to_zero b a
  | a <= 0 && 0 <= b = 0
  | 0 <= a = a
  | b <= 0 = b

solve :: [Int] -> Int
solve [x,y,a,b] = d2 * b + d1 * a
  where d1 = abs (x-y)
        d2 = dist_to_zero x y
solve x = undefined

lines_to_pairs [] = []
lines_to_pairs (x:y:zz) = (unwords [x,y]):(lines_to_pairs zz)

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

import qualified Data.List as L

dist_to_zero a b
  | a > b = dist_to_zero b a
  | a <= 0 && 0 <= b = 0
  | 0 <= a = a
  | b <= 0 = b

solve :: [Int] -> Int
solve [x,y,a,b] = d2 * (min b (2*a)) + d1 * a
  where d1 = abs (x-y)
        d2 = dist_to_zero x y
solve x = undefined

lines_to_pairs [] = []
lines_to_pairs (x:y:zz) = (unwords [x,y]):(lines_to_pairs zz)

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

solve :: [Int] -> Int
solve (0:0:_) = 0
solve (0:y:a:b:_) = a*y
solve (x:0:a:b:_) = a*x
solve (x:y:a:b:_)
    | b > 2*a =  x*a + y*a
    | b <= 2*a = (min x y)*b + (abs (x - y))*a

test :: (Int) -> IO()
test 0 = return()
test x = do
    l1 <- getLine
    l2 <- getLine
    let t = l1 ++ " " ++ l2
    let arr = map (\a -> read a :: Int ) $ words t
    let ans = solve arr
    let out = show ans
    putStrLn out
    test (x - 1)

main = do
    t <- getLine
    let x = read t :: Int

    test x

solve1 :: Int -> Int -> Int -> Int -> Int
solve1 x y a b
    | x * y <= 0        = a* (abs x+ abs y)
    | b > 2*a           = a* (abs x + abs y)
    | otherwise         = a* abs (abs x - abs y) + b* min (abs x) (abs y)

solveTestCases :: Int -> IO ()
solveTestCases 0 = return ()
solveTestCases n = do
    xy <- getLine
    ab <- getLine
    let
        (x:y:_) = map read $ words xy
        (a:b:_) = map read $ words ab
    print $ solve1 x y a b
    solveTestCases (n-1)

main :: IO ()
main = do
    t <- getLine
    solveTestCases (read t)

solve1 :: Int -> Int -> Int -> Int -> Int
solve1 x y a b
    | b > 2*a           = a * (x +y)
    | otherwise         = b * mn + a * (mx - mn)
    where
        mn = min x y
        mx = max x y

solveTestCases :: Int -> IO ()
solveTestCases 0 = return ()
solveTestCases n = do
    xy <- getLine
    ab <- getLine
    let
        (x:y:_) = map read $ words xy
        (a:b:_) = map read $ words ab
    print $ solve1 x y a b
    solveTestCases (n-1)

main :: IO ()
main = do
    t <- getLine
    solveTestCases (read t)

solve1 :: Int -> Int -> Int -> Int -> Int
solve1 x y a b
    | b > 2*a           = a* (x + y)
    | otherwise         = a* abs (x - y) + b* min x y

solveTestCases :: Int -> IO ()
solveTestCases 0 = return ()
solveTestCases n = do
    xy <- getLine
    ab <- getLine
    let
        (x:y:_) = map read $ words xy
        (a:b:_) = map read $ words ab
    print $ solve1 x y a b
    solveTestCases (n-1)

main :: IO ()
main = do
    t <- getLine
    solveTestCases (read t)


-- Try Codeforces
-- author: Leonardone @ NEETSDKASU
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.List (sort)

readI = fst . fromJust . C.readInteger

main = C.interact $ solve . map (map readI . C.words) . C.lines

solve [_, xs, ys] = if ans then "YES" else "NO"
    where
        capa = sum $ take 2 $ reverse $ sort ys
        ans = sum xs <= capa

import Data.Int
import Data.List

solve :: Int64 -> Int64 -> String
solve a b
  | a <= b    = "YES"
  | otherwise = "NO"

main = do
  n <- getLine
  a <- getLine
  b <- getLine
  let
    a'  = sum $ map read $ words a
    b'  = sum $ take 2 $ reverse $ sort $ map read $ words b
    ans = solve a' b'
  putStrLn ans

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where

import Control.Monad
import Control.Monad.Trans.State.Lazy
import qualified Data.ByteString.Char8 as B
import Data.Int
import Data.List
import Data.Bool

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  as <- replicateM n p64
  bs <- replicateM n p64
  return $ bool "NO" "YES" $ solve as bs
  where
  pop = state $ \(x:xs) -> (x, xs)
  p64 = fmap fromIntegral poi
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve as bs = (sum as :: Int64) <= sum (take 2 $ sortBy (flip compare) bs)

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

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

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

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

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

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    xs <- getLine >>= return . map readInteger . words
    ys <- getLine >>= return . map readInteger . words
    let twoMaxCans = sum $ take 2 $ reverse $ sort ys
        allCans = sum xs
    putStrLn $ yesNo $ allCans <= twoMaxCans

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

import Data.List (sort)

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

solve [_, xs, ys] = if ans then "YES" else "NO"
    where
        capa = sum $ take 2 $ reverse $ sort xs
        ans = sum xs <= capa

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.List (sort)

readI = fst . fromJust . C.readInt

main = C.interact $ solve . map (map readI . C.words) . C.lines

solve [_, xs, ys] = if ans then "YES" else "NO"
    where
        capa = sum $ take 2 $ reverse $ sort ys
        ans = sum xs <= capa

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.List (sort)

readI = fst . fromJust . C.readInt

main = C.interact $ solve . map (map readI . C.words) . C.lines

solve [_, xs, ys] = if ans then "YES" else "NO"
    where
        capa = sum $ take 2 $ reverse $ sort xs
        ans = sum xs <= capa

import Data.List

solve :: Int -> Int -> String
solve a' b'
  | a' <= b'  = "YES"
  | otherwise = "NO"

main = do
  n <- getLine
  a <- getLine
  b <- getLine
  putStrLn (solve (sum $ map read $ words a) (sum $ take 2 $ reverse $ sort $ map read $ words b))

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

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

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

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

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

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    xs <- getLine >>= return . map readInteger . words
    ys <- getLine >>= return . map readInteger . words
    let twoMaxCans = sum $ take 2 $ reverse $ sort ys
        allCans = sum xs
    putStrLn $ yesNo $ allCans < twoMaxCans


import Data.List
import Control.Monad

bogosort :: (Ord a) => [a] -> [a]
bogosort = reverse . sort

main = do
  i <- getLine
  let t = read i :: Int
  forM_ [1..t] $ \_ -> do
    j <- getLine
    ss <- getLine
    let xx = map (\x -> read x :: Int) $ words ss
    let ret = bogosort xx
    putStrLn (intercalate " " (map show ret))

import Control.Monad

reverseqs :: [Int] -> [Int]
reverseqs [] = []
reverseqs (x:xs) = let greater = reverseqs (filter (>= x) xs)
                       lesser = reverseqs (filter (< x) xs)
                    in greater ++ [x] ++ lesser

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

main = do
    t <- getLine
    let cases = (read t :: Int)
    results <- forM [1..cases] (\t -> do
        integers <- readInts
        array <- readInts
        let final = foldl (\acc x ->  acc ++ (show x) ++ " ") ""  $ reverseqs array
        return final
        )

    mapM putStrLn results

import Data.List
import Control.Monad
import Data.STRef

(|>) x f = f x

main = do
    line <- getLine
    forM_ [1..(read line)] $ \t -> do
        line <- getLine
        line <- getLine
        list <- words line |> map (read :: String -> Int) |> sort |> reverse |> pure
        forM_ list $ \x -> do
            putStr (show x)
            putStr " "
        putStrLn ""

import Data.List
import Control.Monad

bogosort :: (Ord a) => [a] -> [a]
bogosort = reverse . sort

main = do
  i <- getLine
  let t = read i :: Int
  forM_ [1..t] $ \_ -> do
    j <- getLine
    ss <- getLine
    let xx = words ss
    let ret = bogosort xx
    putStrLn (intercalate " " ret)


{-# LANGUAGE BangPatterns #-}

import Data.List (foldl', unfoldr) -- '
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy.Char8 (readInt)

type Trip = (Int, Int, Int)

step :: Trip -> Int -> Trip
step (!ix, !prev, !best) v
  | ix < v     = (ix, minBound, best)
  | otherwise  = (ix, nv, nbv)  where
    nv = v + max (-ix) prev
    nbv = max nv best

solve1 :: Int -> [Int] -> Trip
solve1 maxv = foldl' step (maxv, minBound, minBound) -- '

solve :: [Int] -> Int
solve li = maximum [bv | (_, _, bv) <- map (`solve1` li) [-30 .. 30]]

parse :: L.ByteString -> [Int]
parse = parseLine . L.dropWhile (== newline) . L.dropWhile (/= newline)  where
  newline = 0x0a
  space = 0x20
  parseLine = unfoldr (readInt . L.dropWhile (== space))

main :: IO ()
main = (putStr . (++ "\n") . show . solve . parse) =<< L.getContents

import Data.List (unfoldr, foldl') -- '
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy.Char8 (readInt)

step :: Int -> Int -> Int -> Int
step maxv prev v
  | maxv < v     = minBound
  | otherwise  = v + max (-maxv) prev

mymax :: [Int] -> Int
mymax = foldl' max minBound -- '

solve :: [Int] -> Int
solve li = mymax $ concatMap (\maxv -> scanl (step maxv) minBound li) [-30..30]

parse :: L.ByteString -> [Int]
parse = parseLine . L.dropWhile (== newline) . L.dropWhile (/= newline)  where
  newline = 0x0a
  space = 0x20
  parseLine = unfoldr (readInt . L.dropWhile (== space))

main :: IO ()
main = (putStr . (++ "\n") . show . solve . parse) =<< L.getContents

-- Verdict: TLE.
-- GHC probably isn't reuse the input array or preallocating for step.
-- Probably fixable in Haskell, but not as easy as I'd like it to be.
-- The lack of language-level support for unique refs and
-- pure functions that consume their args hurts at a time like this.

{-# LANGUAGE BangPatterns #-}

--import Data.Array (Array, listArray, elems)
import Data.List (foldl', unfoldr) -- '
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy.Char8 (readInt)

type Array x = []
listArray :: (x,x) -> [y] -> Array x y
listArray _ = id
elems :: Array x y -> [y]
elems = id

type Arr = Array Int (Int, Int, Int)

startArr :: Arr
startArr = listArray (-30, 30) [(i, minBound, minBound) | i <- [-30 .. 30]]

step :: Arr -> Int -> Arr
step arr v = fmap step1 arr  where
  step1 (!ix, !prev, !best)
    | ix < v     = (ix, minBound, best)
    | otherwise  = seq nv $ seq nbv (ix, nv, nbv)  where
      nv = v + max (-ix) prev
      nbv = max nv best

solve :: [Int] -> Int
solve li = maximum [bv | (_, _, bv) <- elems (foldl' step startArr li)]

parse :: L.ByteString -> [Int]
parse = parseLine . L.dropWhile (== newline) . L.dropWhile (/= newline)  where
  newline = 0x0a
  space = 0x20
  parseLine = unfoldr (readInt . L.dropWhile (== space))

main :: IO ()
main = (putStr . (++ "\n") . show . solve . parse) =<< L.getContents

import Data.List (unfoldr, foldl') -- '
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Lazy.Char8 (readInt)

step :: Int -> Int -> Int -> Int
step maxv prev v
  | maxv < v     = minBound
  | otherwise  = v + max (-maxv) prev

mymax :: [Int] -> Int
mymax = foldl' max minBound -- '

solve :: [Int] -> Int
solve li = mymax $ concatMap (\maxv -> scanl (step maxv) minBound li) [-30..30]

parse :: L.ByteString -> [Int]
parse = parseLine . L.dropWhile (== newline) . L.dropWhile (/= newline)  where
  newline = 0x0a
  space = 0x20
  parseLine = unfoldr (readInt . L.dropWhile (== space))

main :: IO ()
main = (putStrLn . show . solve . parse) =<< L.getContents

import Data.Array (Array, listArray, assocs)
import Data.List (foldl') -- '

type Arr = Array Int (Int, Int)

startArr :: Arr
startArr = listArray (-30, 30) (replicate 61 (minBound, minBound))

step :: Arr -> Int -> Arr
step arr v = listArray (-30, 30) [step1 i v e | (i, e) <- assocs arr]  where
  step1 ix va (prev, best)
    | ix < va    = (minBound, best)
    | otherwise  = let  nv = va + max 0 prev  in  (nv, max nv best)

solve :: [Int] -> Int
solve li = maximum [bv - i | (i, (_, bv)) <- assocs (foldl' step startArr li)]

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

main :: IO ()
main = interact ((++ "\n") . show . solve . parse)


import System.IO

toint s = (read s) :: Int

doit2 l [] s e ss = doit2 l l s e ss
doit2 l (t:ts) s e ss =
  let m = div (s+e) 2 in
  let a = t * (head ss) in
  ((show m) ++ "\n") ++ (if a == 0 then "" else (if a < 0 then (doit2 l ts s m (tail ss)) else doit2 l ts (m+1) e (tail ss)))

doit m n l s =
  if n == 0 then
    let ll = reverse l in
    doit2 ll ll 1 (m+1) s
  else
    let a = head s in
    "1\n" ++ (if a == 0 then ""  else (doit m (n-1) (a:l) (tail s)))

solve::String->String
solve ss =
  let (m:n:s) = map toint $ words ss in
  doit m n [] s

main = do
    hSetBuffering stdout LineBuffering
    interact solve

import System.IO
import Control.Monad

makeTry :: Int -> IO Int
makeTry x = do
  print x
  hFlush stdout
  readLn

getCorrectness :: Int -> IO [Bool]
getCorrectness n = do
  x <- makeTry 1
  if x == 0 then
    return []
  else replicateM (n - 1) (makeTry 1) >>= \y -> return . map (== 1) $ x : y

doRest :: Int -> Int -> [Bool] -> IO ()
doRest lb ub (x:xs) = do
  let mb = (lb + ub) `div` 2
  ans <- makeTry mb
  let ans' = if x then ans else -ans
  case ans' of
    0 -> return ()
    1 -> doRest (mb + 1) ub xs
    -1 -> doRest lb mb xs

main = do
  [m, n] <- fmap (map read . words) getLine
  l <- getCorrectness n
  if l == [] then return () else doRest 1 (m + 1) $ cycle l

import System.IO

toint s = (read s) :: Int

doit2 l [] s e ss = doit2 l l s e ss
doit2 l (t:ts) s e ss =
  let m = div (s+e) 2 in
  let a = t * (head ss) in
  ((show m) ++ "\n") ++ (if a == 0 then "" else (if a < 0 then (doit2 l ts s m (tail ss)) else doit2 l ts (m+1) e (tail ss)))

doit m n l s =
  if n == 0 then
    let ll = reverse l in
    doit2 ll ll 1 (m+1) s
  else
    let a = head s in
    "1\n" ++ (if a == 0 then ""  else "1\n"++(doit m (n-1) (a:l) (tail s)))

solve::String->String
solve ss =
  let (m:n:s) = map toint $ words ss in
  doit m n [] s

main = do
    hSetBuffering stdout LineBuffering
    interact solve


import Control.Monad
readDoubles = fmap (map read.words) getLine :: IO [Double]

printResult [n,k] = print $ ceiling $ (if k >= n then k else k*y)/n
                where y = fromInteger $ ceiling (n/k) :: Double

main = do
    t <- readLn :: IO Int
    a <- replicateM t readDoubles
    mapM_ printResult a

import Control.Monad
import Data.List
readDoubles = fmap (map read.words) getLine :: IO [Double]

printResult [n,k] = print $ ceiling (r/n)
                where r = if k >= n then k else k * (let y = fromInteger $ ceiling (n/k) :: Double in y)

main = do
    t <- readLn :: IO Int
    a <- replicateM t readDoubles
    mapM_ printResult a

module Main where

import Control.Monad
import Control.Monad.ST
import Data.Array.ST.Safe
import Data.Maybe
import Data.Int
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as BS
--import Debug.Trace

--debug = flip trace
readx = fromInteger . fst . fromJust. BS.readInteger <$> BS.getLine
readxs =  map (fromInteger . fst . fromJust. BS.readInteger) . BS.words <$> BS.getLine

printList :: Show a => [a] -> IO ()
printList [] = return ()
printList [a] = print a
printList (a:xs) = putStr (show a) >> putChar ' ' >> printList xs

solve :: Int64 -> Int64 -> Int64
solve n k = (totSum+n-1) `div` n
    where totSum = k * ((n+k-1) `div` k)

main :: IO()
main =  do
   t <- readx
   replicateM_ t $ do
       (n:k:_) <- readxs
       print $ solve n k

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

main :: IO ()
main = getLine >>= flip replicateM_ test . read

test :: IO ()
test = do
  [n, k] <- map read . words <$> getLine :: IO [Integer]
  print $ if n <= k then (k - 1) `div` n + 1 else if n `mod` k == 0 then 1 else 2

import qualified Data.Set as Set
import Data.List
import Control.Monad
import Data.Char

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

printArray [] = ""
printArray (x:xs) = show(x) ++" " ++ printArray xs

printS = do
    [n,k]<-readInts
    let cf = (div n k) + if (mod n k > 0) then 1 else 0
        r = (div (cf*k) n) + if (mod (cf*k) n > 0) then 1 else 0
    print r

main = do
    t<-readLn::IO Int
    replicateM_ t printS

main = getContents >>= traverse print . solves . map read . tail . words

solves [] = []
solves (n:k:xs) = f n (k * f k n) : solves xs
  where f n k = (n + k - 1) `div` n

solve :: [Int] -> Int
solve [n, k] = m `div` n + ceil
    where rem = n `mod` k
          m = if rem == 0 then n else n + (k - rem)
          ceil = if m `mod` n == 0 then 0 else 1

main :: IO ()
main = interact (unlines . map (show . solve . toArr) . tail . lines)
    where toArr s = map (read :: String -> Int) $ words s

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n, k] <- getInts
    C.putStrLn $ C.pack $ show $ if n > k then (if n `mod` k == 0 then 1 else 2) else (k + n - 1) `div` n

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import qualified Data.Array.Unboxed         as UA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

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

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

solve :: Int64 -> Int64 -> Int64
solve n k
    | n >= k && n `mod` k == 0    = 1
    | n >= k && n `mod` k /= 0    = 2
    | n < k = (k + n - 1) `div` n

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, k] <- B8.getLine <&> map readIntegerB8 . B8.words
        let answer = solve (fromInteger n) (fromInteger k)
        printf "%lld\n" answer

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import qualified Data.ByteString.Lazy.Char8 as P

import Data.List
import Data.Int

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put . P.tail . snd $ P.break (== '\n') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, k] <- readInts
    let
      k' = k * div (n+k-1) k
      (q', r) = divMod k' n
      ans = q' + if  r > 0  then  1  else  0
    lift . P.putStrLn . P.pack $ {- unwords $ map -} show ans

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import qualified Data.ByteString.Lazy.Char8 as P

import Data.List
import Data.Int

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put . P.tail . snd $ P.break (== '\n') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, k] <- readInts
    let
      (q, r) = divMod k n
      ans = q + if  r > 0 || q == 0  then  1  else  0
    lift . P.putStrLn . P.pack $ {- unwords $ map -} show ans

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import qualified Data.ByteString.Lazy.Char8 as P

import Data.List
import Data.Int

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put . P.tail . snd $ P.break (== '\n') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, k] <- readInts
    let
      (q, r) = divMod k n
      q' = max q 1
      --ans = concat $ zipWith replicate [r, n-r] [q+1, q]
      ans = q' + if  r > 0  then  1  else  0
    lift . P.putStrLn . P.pack $ {- unwords $ map -} show ans

module Main where

import Control.Monad
import Control.Monad.ST
import Data.Array.ST.Safe
import Data.Maybe
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as BS
--import Debug.Trace

--debug = flip trace
readx = fromInteger . fst . fromJust. BS.readInteger <$> BS.getLine
readxs =  map (fromInteger . fst . fromJust. BS.readInteger) . BS.words <$> BS.getLine

printList :: Show a => [a] -> IO ()
printList [] = return ()
printList [a] = print a
printList (a:xs) = putStr (show a) >> putChar ' ' >> printList xs

solve :: Int -> Int -> Int
solve n k = (totSum+n-1) `div` n
    where totSum = k * ((n+k-1) `div` k)

main :: IO()
main =  do
   t <- readx
   replicateM_ t $ do
       (n:k:_) <- readxs
       print $ solve n k

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

main :: IO ()
main = getLine >>= flip replicateM_ test . read

test :: IO ()
test = do
  [n, k] <- map read . words <$> getLine :: IO [Integer]
  print $ if n > k then 2 else (k - 1) `div` n + 1


import Control.Monad
import Data.List

main = do
  q <- readLn
  replicateM (q :: Int) $ do
    getLine
    a <- map read . words <$> getLine
    print $ sum $ scanl1 (\x -> \y -> max 0 $ min (x-1) y) $ reverse . sort . map length . group . sort $ (a :: [Int])

import Data.List

readInt :: String -> Integer
readInt = read

main = interact $ solve . (map ((map readInt) . words)) . tail . lines

solve :: [[Integer]] -> String
solve [] = ""
solve (_:x:xs) = solveInstance x ++ solve xs

solveInstance :: [Integer] -> String
solveInstance xs =
    let l = reverse $ sort $ map genericLength $ groupBy (==) $ sort xs in
--    (++"\n") $ show l
    (++"\n") . show $ takeGreedily l (head l) 0

takeGreedily :: [Integer] -> Integer -> Integer -> Integer
takeGreedily [] _ _ = 0
takeGreedily _ 0 _ = 0
takeGreedily (x:xs) current carry
    | x >= current = current + takeGreedily xs (current - 1) carry
    | carry >= 1 = current + takeGreedily (x:xs) (current - 1) (carry - 1)
    | otherwise = takeGreedily (x:xs) (current - 1) carry

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

input :: Read a => IO [a]
input = map read <$> words <$> getLine

main = do
  [q] <- input
  replicateM_ q $ do
    getLine
    a <- input :: IO [Integer]
    let f = reverse $ sort $ map length $ group $ sort a
    print $ sum $ scanl1 (\b x -> max 0 $ min (b-1) x) f

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

input :: Read a => IO [a]
input = map read <$> words <$> getLine

main = do
  [q] <- input
  replicateM_ q $ do
    getLine
    a <- input :: IO [Int]
    let f = reverse $ sort $ map length $ group $ sort a
    print $ sum $ scanl1 (\b x -> max 0 $ min (b-1) x) f

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

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

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

main = do
  q <- readInt
  replicateM_ q $ do
    getLine
    a <- readInts
    let f = reverse $ sort $ map length $ group $ sort a
    print $ sum $ scanl1 (\b x -> max 0 $ min (b-1) x) f


{-# LANGUAGE ScopedTypeVariables #-}

import Text.Printf
import Data.List
import Data.Functor
import Data.Function
import Control.Monad
import Data.Maybe
import Data.Foldable (foldr', foldr1)
import Prelude
import Control.Monad.State.Strict
import qualified Data.ByteString.Char8 as B8
import qualified Data.Map.Strict as MapS
import qualified Data.Set as Set

readB8Int :: B8.ByteString -> Int
readB8Int = fst . fromJust . B8.readInt

main :: IO ()
main = do
    [n, m] <- (map readB8Int) <$> B8.words <$> B8.getLine
    (squares :: [Int]) <- (map readB8Int) <$> B8.words <$> B8.getLine
    let sizes :: MapS.Map Int Int = foldr' (MapS.alter (fmap (+1) . flip mplus (Just 0))) MapS.empty squares
    let minSize = (foldr1 min) . map (\i -> fromMaybe 0 . MapS.lookup i $ sizes) $ [1..n]
    printf "%d\n" minSize

main = do
  [n, m] <- getLine >>= return. map read. words :: IO [Int]
  a <- getLine >>= return. map read. words :: IO [Int]
  print.minimum. map (\x -> length.filter (==x) $ a) $ [1..n]

import Data.Array

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

main = do
    [n,m] <- getInts
    columns <- getInts
    let heights = accumArray (+) 0 (1,n) [(i,1) | i <- columns]
    print $ (minimum . elems) heights

{-# OPTIONS_GHC -O2 #-}
import Control.Applicative
import Data.List
getList = fmap ((map read).words) getLine
get c = sort $ map length (group (sort c))
solve n c
  | length (get c) < n = show 0
  | otherwise = show (head (get c))
main = do
  [n,_] <- getList
  c <- getList
  putStrLn $ solve n c

import Data.List

main = getContents >>= print . solve . map read . words

solve (x:_:xs) = subtract 1 $ minimum $ map length $ group $ sort $ [1 .. x] ++ xs

import Control.Applicative
import Data.List
getList = fmap ((map read).words) getLine
get c = reverse $ map length (group (sort c))
solve n c
  | length (get c) < n = show 0
  | otherwise = show (head (get c))
main = do
  [n,_] <- getList
  c <- getList
  putStrLn $ solve n c

{-# LANGUAGE ScopedTypeVariables #-}

import Text.Printf
import Data.List
import Data.Functor
import Data.Function
import Control.Monad
import Data.Maybe
import Data.Foldable (foldr', foldr1)
import Prelude
import Control.Monad.State.Strict
import qualified Data.ByteString.Char8 as B8
import qualified Data.Map.Strict as MapS
import qualified Data.Set as Set

readB8Int :: B8.ByteString -> Int
readB8Int = fst . fromJust . B8.readInt

main :: IO ()
main = do
    [n, m] <- (map readB8Int) <$> B8.words <$> B8.getLine
    (squares :: [Int]) <- (map readB8Int) <$> B8.words <$> B8.getLine
    let sizes :: MapS.Map Int Int = foldr' (MapS.alter (fmap (+1) . mplus (Just 1))) MapS.empty squares
    let minSize = (foldr1 min) . map (\i -> fromMaybe 0 . MapS.lookup i $ sizes) $ [1..n]
    printf "%d\n" minSize

{-# LANGUAGE ScopedTypeVariables #-}

import Text.Printf
import Data.List
import Data.Functor
import Data.Function
import Control.Monad
import Data.Maybe
import Data.Foldable (foldr', foldr1)
import Prelude
import Control.Monad.State.Strict
import qualified Data.ByteString.Char8 as B8
import qualified Data.Map.Strict as MapS
import qualified Data.Set as Set

readB8Int :: B8.ByteString -> Int
readB8Int = fst . fromJust . B8.readInt

main :: IO ()
main = do
    [n, m] <- (map readB8Int) <$> B8.words <$> B8.getLine
    (squares :: [Int]) <- (map readB8Int) <$> B8.words <$> B8.getLine
    let sizes :: MapS.Map Int Int = foldr' (MapS.alter (fmap (+1) . flip mplus (Just 1))) MapS.empty squares
    let minSize = (foldr1 min) . map (\i -> fromMaybe 0 . MapS.lookup i $ sizes) $ [1..n]
    printf "%d\n" minSize

main = do
  [n, m] <- getLine >>= return. map read. words :: IO [Int]
  a <- getLine >>= return. map read. words :: IO [Int]
  print.maximum. map (\x -> length.filter (==x) $ a) $ [1..n]


module Main where

import Data.STRef
import Data.Array
import Data.Array.ST
import Data.Array.MArray
import Control.Monad
import Data.List

main = do
    inputNMK <- getLine
    let [n, m, k] = map read $ words inputNMK

    teeth <- replicateM n $ do
        inputRC <- getLine
        let [r, c] = map read $ words inputRC

        return (r, c)

    let rowViability = runSTArray $ do
            rowViability <- newArray (1, m) 2147483647
            forM_ teeth $ \(r, c) -> do
                old_c <- readArray rowViability r
                if c < old_c
                    then writeArray rowViability r c
                    else return ()
            return rowViability

    putStrLn $ show $ min k $ sum $ elems rowViability

import Prelude
import List
import Char

main = interact q

q = func.lines

func::[String]->String
func (a:xs) = func' (words a) xs
              where
                func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)
                                      ++"\n"++ (func (drop a' xs))
                                      where a' = toInt a
                                            b' = toInt b
                                            c' = asInteger c
                                            makeTooth xs = (((toInt.head) xs),
                                                           ((asInteger.last) xs))
func []     = ""

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Integer->String
toString = show

solve::Int->Int->Integer->[(Int,Integer)]->Integer
solve a b c  = min c.sum.map (minimum.map snd).groupBy groupHelper.sortBy sorter
               where
                 sorter::(Int,Integer)->(Int,Integer)->Ordering
                 sorter a b = compare (fst a) (fst b)
                 groupHelper::(Int,Integer)->(Int,Integer)->Bool
                 groupHelper a b = (fst a) == (fst b)

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

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

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
      -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
  n : m : k : _ <- readData
  v <- fmap (sum . map (snd . head) . groupBy ((==) `on` fst) . sort)
      . T.for [1 .. n] $ \i -> do
    r : c : _ <- readData
    return (r, c)
  print $ min v k

main = interact (ans)
ans theInput = show $ min (sum $ viability teeth) k where
	theLines = lines theInput
	[n,m,k] = map (read::String->Int) (words $ head theLines)
	teeth = map (map (read::String->Int)) (map words (take n (tail theLines)))
	viability [] = take m (repeat 1000001)
	viability (x:xs) = v1 ++ [v2] ++ v3 where
		r = x !! 0
		v = viability xs
		v1 = take (r-1) v
		v2 = min (v !! (r-1)) (x !! 1)
		v3 = drop r v

import Array

bigNum = 1000000

solve :: Int -> [(Int, Int)] -> Int
solve n assocs' = foldl (+) 0 elements
  where
    elements = elems (accumArray min bigNum (1, n) assocs')

readAssoc :: Int -> IO (Int, Int)
readAssoc _ = do
  line <- getLine
  let [a, b] = map read $ words line
  return (a, b)

main = do
  line <- getLine
  let [n, m, k] = map read $ words line
  assocs' <- sequence (map readAssoc [1..n])
  print $ min (solve m assocs') k

module Main where

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

main = do
  [n, m, k] <- map read . words <$> getLine
  let readline :: IO (Integer, Integer)
      readline = do
         [row, rv] <- map read . words <$> getLine
         return (row, rv)
  lst <- replicateM n readline
  let lst' = nubBy ((==) `on` fst) . sort $ lst
      total = sum' . map snd $ lst'
      sum'  = foldl1' (+)
  print (min total (fromIntegral k))

import Array

bigNum = 10000

solve :: Int -> [(Int, Int)] -> Int
solve n assocs' = foldl (+) 0 elements
  where
    elements = elems (accumArray min bigNum (1, n) assocs')

readAssoc :: Int -> IO (Int, Int)
readAssoc _ = do
  line <- getLine
  let [a, b] = map read $ words line
  return (a, b)

main = do
  line <- getLine
  let [n, m, k] = map read $ words line
  assocs' <- sequence (map readAssoc [1..n])
  print $ min (solve m assocs') k

import Prelude
import List
import Char

main = interact q

q = func.lines

func::[String]->String
func (a:xs) = func' (words a) xs
              where
                func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)
                                      ++ (func (drop a' xs))
                                      where a' = toInt a
                                            b' = toInt b
                                            c' = asInteger c
                                            makeTooth xs = (((toInt.head) xs),
                                                           ((asInteger.last) xs))
func []     = ""

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Integer->String
toString = show

solve::Int->Int->Integer->[(Int,Integer)]->Integer
solve a b c  = min (toInteger c).sum.map (maximum.map snd).groupBy groupHelper.sortBy sorter
               where
                 sorter::(Int,Integer)->(Int,Integer)->Ordering
                 sorter a b = compare (fst a) (fst b)
                 groupHelper::(Int,Integer)->(Int,Integer)->Bool
                 groupHelper a b = (fst a) == (fst b)

import Prelude
import List
import Char

main = interact q

q = func.lines

func::[String]->String
func (a:xs) = func' (words a) xs
              where
                func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)
                                      ++"\n"++ (func (drop a' xs))
                                      where a' = toInt a
                                            b' = toInt b
                                            c' = asInteger c
                                            makeTooth xs = (((toInt.head) xs),
                                                           ((asInteger.last) xs))
func []     = ""

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Integer->String
toString = show

solve::Int->Int->Integer->[(Int,Integer)]->Integer
solve a b c  = min c.sum.map (maximum.map snd).groupBy groupHelper.sortBy sorter
               where
                 sorter::(Int,Integer)->(Int,Integer)->Ordering
                 sorter a b = compare (fst a) (fst b)
                 groupHelper::(Int,Integer)->(Int,Integer)->Bool
                 groupHelper a b = (fst a) == (fst b)

import Prelude
import List
import Char

main = interact (func.lines)

func::[String]->String
func (a:xs) = func' (words a) xs
              where
                func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)
                                      ++ (func (drop a' xs))
                                      where a' = toInt a
                                            b' = toInt b
                                            c' = asInteger c
                                            makeTooth xs = (((toInt.head) xs),
                                                           ((asInteger.last) xs))
func []     = ""

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Integer->String
toString = show

solve::Int->Int->Integer->[(Int,Integer)]->Integer
solve a b c  = min (toInteger a).maximum.map (maximum.map snd).groupBy groupHelper.sortBy sorter
               where
                 sorter::(Int,Integer)->(Int,Integer)->Ordering
                 sorter a b = compare (fst a) (fst b)
                 groupHelper::(Int,Integer)->(Int,Integer)->Bool
                 groupHelper a b = (fst a) == (fst b)

import Prelude
import List
import Char

main = interact q

q = func.lines

func::[String]->String
func (a:xs) = func' (words a) xs
              where
                func' (a:b:c:[]) xs = ((toString.solve a' b' c'.map (makeTooth.words).take a') xs)
                                      ++ (func (drop a' xs))
                                      where a' = toInt a
                                            b' = toInt b
                                            c' = asInteger c
                                            makeTooth xs = (((toInt.head) xs),
                                                           ((asInteger.last) xs))
func []     = ""

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Integer->String
toString = show

solve::Int->Int->Integer->[(Int,Integer)]->Integer
solve a b c  = min c.sum.map (maximum.map snd).groupBy groupHelper.sortBy sorter
               where
                 sorter::(Int,Integer)->(Int,Integer)->Ordering
                 sorter a b = compare (fst a) (fst b)
                 groupHelper::(Int,Integer)->(Int,Integer)->Bool
                 groupHelper a b = (fst a) == (fst b)

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

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

main :: IO ()
main = do
  let readData :: IO [Int]
      readData = map read . words <$> getLine
      -- readData = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine
      exit = print (-1) >> exitSuccess
  s1 <- getLine
  s2 <- getLine
  when (length s1 /= length s2) $  exit
  n <- readLn
  cs <- T.for [1 .. n] $ \i -> do
    from : to : v: _ <- words <$> getLine
    return (head from, Map.singleton (head to) (read v :: Int))
  let mp = Map.fromListWith (Map.unionWith min) cs
      bnds = (('a', 'a'), ('z', 'z'))
  table <- newArray bnds maxBound :: IO (IOArray (Char, Char) Int)
  F.for_ (zip ['a' .. 'z'] ['a' .. 'z']) $ \idx -> do
    writeArray table idx 0
  let fill from cost now = F.for_ (Map.lookup now mp) $ \mp' -> do
        F.for_ (Map.toList mp') $ \(to, new) -> do
          old <- readArray table (now, to)
          when (old == maxBound || new < old) $ do
            writeArray table (now, to) new
            let new' = cost + new
            old' <- readArray table (from, to)
            when (old' == maxBound || new' < old') $ do
              writeArray table (from, to) new'
            fill from new' to
  F.for_ ['a' .. 'z'] $ \c -> fill c 0 c
  F.for_ ['a' .. 'z'] $ \c -> fill c 0 c
  let check c1 c2
        | c1 == c2  = return (c1, 0)
        | otherwise = do
            xs <- T.for ['a' .. 'z'] $ \to -> do
              v1 <- readArray table (c1, to)
              v2 <- readArray table (c2, to)
              case () of
                _ | c1 == to  -> return (to, v2)
                  | c2 == to  -> return (to, v1)
                  | otherwise -> return (to, min v1 v2)
            when (null xs) $ exit
            let (c, cost) = minimumBy (comparing snd) xs
            if cost == maxBound
              then exit
              else do
                return (c, cost)
  (answer, cost) <- unzip <$> zipWithM check s1 s2
--  getAssocs table >>= printf "%s\n" . show
  print $ sum cost
  putStrLn answer

{-
ad
ad
6
a b 1
a e 4
b e 1
b c 2
c d 100
e d 5
-}


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List hiding (insert)
import qualified Data.Map as M
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

data Heap a = Fork !a [Heap a] | Empty

singleton :: a -> Heap a
singleton x = Fork x []

isEmpty :: Heap a -> Bool
isEmpty Empty = True
isEmpty _ = False

insert :: Ord a => a -> Heap a -> Heap a
insert x h = merge (Fork x []) h

maxElem :: Heap a -> Maybe a
maxElem (Fork x _) = Just x
maxElem _ = Nothing

deleteMax :: Ord a => Heap a -> Maybe (Heap a)
deleteMax (Fork _ hs) = Just $ mergePairs hs
deleteMax _ = Nothing

deleteFindMax :: Ord a => Heap a -> Maybe (a, Heap a)
deleteFindMax (Fork x hs) = Just (x, mergePairs hs)
deleteFindMax _ = Nothing

merge :: Ord a => Heap a -> Heap a -> Heap a
merge hx@(Fork x _) hy@(Fork y _)
  | x >= y    = join hx hy
  | otherwise = join hy hx
 where
   join (Fork x hs) h = Fork x (h:hs)
merge Empty hy = hy
merge hx _ = hx

mergePairs :: Ord a => [Heap a] -> Heap a
mergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)
mergePairs [x]      = x
mergePairs []       = Empty

main :: IO ()
main = do
  [n,x] <- map read.words <$> getLine
  thms <- parse.map readInt.B.words <$> B.getContents
  print $ solve n x thms

parse :: [Int] -> [(Bool, Int, Int)]
parse (1:h:m:rest) = (True,h,m)  : parse rest
parse (0:h:m:rest) = (False,h,m) : parse rest
parse _ = []

solve :: Int -> Int -> [(Bool, Int, Int)] -> Int
solve n x thms = max (goF x 0 Empty Empty fs cs) (goC x 0 Empty Empty fs cs)
   where
     fs = sort[(h,m)|(True,h,m)<-thms]
     cs = sort[(h,m)|(False,h,m)<-thms]
     goF !x !cnt !canUseF !canUseC fs cs
       | Just (m, canUseF'')<-deleteFindMax canUseF' = goC (x+m) (cnt+1) canUseF'' canUseC fs' cs
       | otherwise = cnt
      where
        (ms, fs') = span ((<=x).fst) fs
        !canUseF' = foldl' (flip insert) canUseF $ map snd ms
     goC !x !cnt !canUseF !canUseC fs cs
       | Just (m, canUseC'')<-deleteFindMax canUseC'= goF (x+m) (cnt+1) canUseF canUseC'' fs cs'
       | otherwise = cnt
      where
        (ms, cs') = span ((<=x).fst) cs
        !canUseC' = foldl' (flip insert) canUseC $ map snd ms

import Data.Array.IO
import Data.IORef
import Control.Monad
import Data.Tuple
import Data.List
import Data.Char
import qualified Data.ByteString.Lazy as B

parse :: B.ByteString -> [Int]
parse s = do
	q <- B.splitWith (\x-> x == 13 || x == 10 || x == 32) s
	if B.length q == 0 then
		[]
	else
		return $ foldl' (\a b-> a * 10 + (fromIntegral b) - (ord '0')) 0 (B.unpack q)

readc :: [Int] -> [(Int, Int, Int)]
readc [] = []
readc (t:h:m:xx) = (t,m,h):(readc xx)

spl :: [(Int, Int, Int)] -> ([(Int, Int)], [(Int, Int)])
spl [] = ([], [])
spl ((t, m, h):xs) = let (q0, q1) = spl xs in
	if t == 0 then ((m, h):q0, q1)
	else (q0, (m, h):q1)

getmaxnum :: [(Int, Int)] -> [(Int, Int)] -> Int -> IO Int
getmaxnum [] _ _ = return 0
getmaxnum xs ns x = do
	let aval = filter (\(_,b) -> b <= x) xs
	--putStrLn $ show aval
	if aval == [] then return 0
	else do
		let (mm, mh) = maximum aval
		r <- getmaxnum ns (delete (mm, mh) xs) (x + mm)
		return $ r + 1

main :: IO ()
main = do
	bbbb <- B.getContents
	let n:x:nn = parse bbbb
	let cs = readc nn
	let (kars, leds) = spl cs
	--putStrLn $ show $ (kars, leds)
	r1 <- getmaxnum kars leds x
	r2 <- getmaxnum leds kars x
	let res = max r1 r2
	putStrLn $ show res

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,x] <- map read.words <$> getLine
  thms <- parse.map readInt.B.words <$> B.getContents
  print $ solve n x thms

parse :: [Int] -> [(Bool, Int, Int)]
parse (1:h:m:rest) = (True,h,m)  : parse rest
parse (0:h:m:rest) = (False,h,m) : parse rest
parse _ = []

solve :: Int -> Int -> [(Bool, Int, Int)] -> Int
solve n x thms = max (goF x 0 IS.empty IS.empty fs cs) (goC x 0 IS.empty IS.empty fs cs)
   where
     fs = sort[(h,m)|(True,h,m)<-thms]
     cs = sort[(h,m)|(False,h,m)<-thms]
     goF !x !cnt !canUseF !canUseC fs cs
       | IS.null canUseF' = cnt
       | (m, canUseF'')<-IS.deleteFindMax canUseF' = goC (x+m) (cnt+1) canUseF'' canUseC fs' cs
      where
        (ms, fs') = span ((<=x).fst) fs
        !canUseF' = foldl' (flip IS.insert) canUseF $ map snd ms
     goC !x !cnt !canUseF !canUseC fs cs
       | IS.null canUseC' = cnt
       | (m, canUseC'')<-IS.deleteFindMax canUseC'= goF (x+m) (cnt+1) canUseF canUseC'' fs cs'
      where
        (ms, cs') = span ((<=x).fst) cs
        !canUseC' = foldl' (flip IS.insert) canUseC $ map snd ms

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,x] <- map read.words <$> getLine
  thms <- parse.map readInt.B.words <$> B.getContents
  print $ solve n x thms

parse :: [Int] -> [(Bool, Int, Int)]
parse (1:h:m:rest) = (True,h,m)  : parse rest
parse (0:h:m:rest) = (False,h,m) : parse rest
parse _ = []

solve :: Int -> Int -> [(Bool, Int, Int)] -> Int
solve n x thms = max (goF x 0 IS.empty fs cs) (goC x 0 IS.empty fs cs)
   where
     fs = sort[(h,m)|(True,h,m)<-thms]
     cs = sort[(h,m)|(False,h,m)<-thms]
     goF !x !cnt !canUse fs cs
       | IS.null canUse' = cnt
       | (m, canUse'')<-IS.deleteFindMax canUse' = goC (x+m) (cnt+1) canUse'' fs' cs
      where
        (ms, fs') = span ((<=x).fst) fs
        !canUse' = foldl' (flip IS.insert) canUse $ map snd ms
     goC !x !cnt !canUse fs cs
       | IS.null canUse' = cnt
       | (m, canUse'')<-IS.deleteFindMax canUse'= goF (x+m) (cnt+1) canUse'' fs cs'
      where
        (ms, cs') = span ((<=x).fst) cs
        !canUse' = foldl' (flip IS.insert) canUse $ map snd ms


main = interact $ show . solve . tail . lines
solve [s] = sum $ map fst $ filter ((`elem` "2468") . snd) $ zip [1..] s

import Data.Char
evenSubstrings :: String -> Int
evenSubstrings s = sum $ map f $ (zip s [1..])
f (x,y)
  | even $ digitToInt x = y
  | otherwise           = 0
main = interact $ show . evenSubstrings . (!! 1) . lines

{-# LANGUAGE BangPatterns, Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.List
import Data.Int

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

ceven !c = even $ ord c

solve :: [C.ByteString] -> Builder
solve (sn:s:_) = int64Dec res <> char7 '\n'
  where
    res :: Int64
    res = sum $ map (fromIntegral . fst) $ filter (ceven . snd) $ zip [1 .. ] $ C.unpack $ C.take (ri sn) s

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

main = interact $ show.helper.words

helper (x:xs:_) = fonk 0 1 xs
                 where fonk res _ [] = res
                       fonk res i (a:aa) = if (even.read) (a:"")
                                           then fonk (res + i) (i+1) aa
                                           else fonk (res) (i+1) aa

import Control.Applicative
import Control.Monad
import Data.Char

main= do
		n<- read <$> getLine ::IO [Int]
		s<-map digitToInt <$> getLine
		print $ sum $ zipWith (\a b-> if even b then a else 0)  [1..] s

--ghc 7.10

import Data.List(findIndices)

countEvenSubstrings :: [Int] -> Int
countEvenSubstrings = sum . map (+1) . findIndices (even)

main = do
    nStr <- getLine
    str <- getLine
    let xs = map read . map (:[]) $ str
    print $ countEvenSubstrings xs

import Data.Char

solve _ [] = 0
solve n (x:xs) | digitToInt x `mod` 2 == 0 = (n + 1) + solve (n + 1) xs
               | otherwise                 = solve (n + 1) xs

main = do
    input <- getContents
    let s = last $ lines input
    print $ solve 0 s

import Data.Char
main = interact $ show  . evensubstr . last . lines

evensubstr :: String -> Int
evensubstr s = sum $ map es $ (zip s [1,2..])
  where es (x, y)
          | even $ digitToInt x = y
          | otherwise           = 0

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

evenSubstrings :: String -> Int
evenSubstrings = fst . foldl (\(a, b) c -> if elem c "02468"
                                           then (a + b, b + 1)
                                           else (a,     b + 1)) (0, 1)

main :: IO ()
main = do
    _ <- readInt
    s <- getLine
    print $ evenSubstrings s

import Data.List (inits, tails)
import Data.Char (digitToInt)

main :: IO ()
main = interact $ unlines . fmap (show . countSub) . tail . words

countSub :: String -> Int
countSub = sum . map fst . filter (even . digitToInt . snd) . zip [1..]

import Data.List
subseq = filter (not . null) . concatMap tails . inits
evenSubstrings = length . filter ((== 0) . (`mod` 2)) . map read . tail . subseq
main = interact $ show . evenSubstrings . (!! 1) . lines


import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n <- read <$> getLine
        a <- map read . words <$> getLine
        print $ n - countMinimums a

countMinimums :: [Int] -> Int
countMinimums a = length $ filter (== minimum  a) a

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

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    _ <- getInts
    (x : xs) <- sort <$> getInts
    C.putStrLn $ C.pack $ show $ length $ dropWhile (== x) xs

evens (x:xs) = x:odds xs
evens _ = []

odds (_:xs) = evens xs
odds _ = []

solution :: [Int] -> String
solution a =
  show $ length a - (length . filter (== (foldr1 min a))) a

main = interact $ unlines . map (solution . map read . words) . odds . tail . lines

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

printResult = do
    n <- readLn :: IO Int
    a <- readInts
    let m = minimum a
        c =  length . filter (==m) $ a
    print $ n - c

main = do
    t <- readLn :: IO Int
    replicateM_ t printResult

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]
solve [x] n = n
solve (x:xs) n = if x == head xs then solve xs (n+1) else n
printS = do
    n<-readLn::IO Int
    a <- readInts
    print $ n - solve (sort a) 1
main = do
    t <- readLn::IO Int
    replicateM_ t printS

main = do
  --text <- readFile "inputt.txt"
  --putStrLn ((unlines . solve . map ((\x -> (map (\y -> read y :: Int) x)) . words) . tail . lines) text)
  interact (unlines . solve . map ((\x -> (map (\y -> read y :: Int) x)) . words) . tail . lines)

solve :: [[Int]] -> [String]
solve [] = []
solve (a : b : lst) = (show (head a - (occr (minelt b) b)) : solve lst)
occr elt [] = 0
occr elt (a : xs)
  | (==) a elt = (+) 1 (occr elt xs)
  | otherwise = (occr elt xs)
minelt [x] = x
minelt (x : xs)
  | (x < t) = x
  | otherwise = t
  where t = minelt (xs)


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

solve = do
    [n, x] <- map read.words <$> getLine :: IO [Int]
    a <- map read.words <$> getLine :: IO [Int]
    let v = drop (n - x) $ take x $ sort a
    let u = drop (n - x) $ take x a
    if u == v then putStrLn "YES" else putStrLn "NO"

main = readLn >>= flip replicateM_ solve

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

solve = do
    [n, x] <- map read.words <$> getLine :: IO [Int]
    a <- map read.words <$> getLine :: IO [Int]
    let v = drop (n - x) $ take x $ sort a
    let u = drop (n - x) $ take x a
    putStrLn $ if u == v then "YES" else "NO"

main = readLn >>= flip replicateM_ solve


-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = print . solve . map read . tail . words =<< getContents

solve (a_:b_:ts_) = ans where
    ans = go 0 0 a_ b_ ts_
    go r _ _ _ []     = r
    go r 0 0 0 ts     = r + sum ts
    go r d 0 0 (1:ts) = go r (d-1) 0 0 ts
    go r d 0 b (1:ts) = go r (d+1) 0 (b-1) ts
    go r d a b (1:ts) = go r d (a-1) b ts
    go r d a 0 (2:ts) = go (r+2) d a 0 ts
    go r d a b (2:ts) = go r d a (b-1) ts

main = interact $ f

f :: String -> String
f = show . g . map read . words

g :: [Int] -> Int
g (n:a:b:ts) = h a b 0 ts

h :: Int -> Int -> Int -> [Int] -> Int
h _ _ _ [] = 0
h 0 0 0 (1:ts) = 1 + h 0 0 0 ts
h 0 0 c (1:ts) = h 0 0 (c - 1) ts
h 0 b c (1:ts) = h 0 (b - 1) (c + 1) ts
h a b c (1:ts) = h (a - 1) b c ts
h a 0 c (2:ts) = 2 + h a 0 c ts
h a b c (2:ts) = h a (b - 1) c ts

process a b c (1:listt)
    |(a == 0)&&(b == 0)&&(c == 0) = (process a b c listt) + 1
    |(a == 0)&&(b == 0)&&(c /= 0) = (process a b (c - 1) listt)
    |(a == 0)&&(b /= 0) = (process a (b - 1) (c + 1) listt)
    |(a /= 0) = (process (a - 1) b  c listt)

process a b c (2:listt)
    |(b == 0) = (process  a b c listt) + 2
    |(b /= 0) = (process  a (b - 1) c listt)

process _ _ _ [] = 0

solution [[n, a, b], listt] = process a b 0 listt

problem_data s = (map$map read).(map words).lines$s::[[Int]]
main = interact$(show.solution.problem_data)

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B

main = do
  [n, a, b] <- fmap readInts B.getLine
  ts <- fmap readInts B.getLine
  print $ solve n a b ts

solve n a b ts = (\(_, _, _, c) -> c) $ foldl go (a, 0, b, 0) ts
  where
    go (!c1, !c1', !c2, !c) t
      | t == 1 && c1 > 0 = (c1 - 1, c1', c2, c)
      | t == 1 && c2 > 0 = (c1, c1' + 1, c2 - 1, c)
      | t == 1 && c1' > 0 = (c1, c1' - 1, c2, c)
      | t == 2 && c2 > 0 = (c1, c1', c2 - 1, c)
      | otherwise = (c1, c1', c2, c + t)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

-- words :: String -> [String] Source #
-- words breaks a string up into a list of words, which were delimited by white space.

-- read :: Read a => String -> a Source # (Here a is an int)
-- The read function reads input from a string, which must be completely consumed by the input process.

main = interact $ f

f :: String -> String
f = show . g . map read . words

g :: [Int] -> Int
-- g (n:a:b:ts) = h a b 0 ts  -- a is the number of 1-person tables,
-- b is the number of 2-person tables, c is the number of 2-person tables with 1 person
-- colon prepends a scalar to the front of a vector
g x = h (g_a x) (g_b x) 0 (g_ts x)

g_a :: [Int] -> Int
g_a x = head (tail x)

g_b :: [Int] -> Int
g_b x = head (tail (tail x))

g_ts :: [Int] -> [Int]
g_ts x = tail (tail (tail x))

h :: Int -> Int -> Int -> [Int] -> Int
h a b c ts =
    if ts == []
    then 0
    else if head ts == 1
         then (if a > 0
               then h (a-1) b c (tail ts)
               else (if b > 0
                     then h a (b-1) (c+1) (tail ts)
                     else (if c > 0
                           then h a b (c-1) (tail ts)
                           else 1 + h a b c (tail ts))))   --Each bracket () contains *one* value
         else -- i.e. else if head ts == 2
              if b > 0
              then h a (b-1) c (tail ts)
              else 2 + h a b c (tail ts)

-- words :: String -> [String] Source #
-- words breaks a string up into a list of words, which were delimited by white space.

-- read :: Read a => String -> a Source # (Here a is an int)
-- The read function reads input from a string, which must be completely consumed by the input process.

main = interact $ f

f :: String -> String
f = show . g . map read . words

g :: [Int] -> Int
g (n:a:b:ts) = h a b 0 ts  -- a is the number of 1-person tables,
-- b is the number of 2-person tables, c is the number of 2-person tables with 1 person

h :: Int -> Int -> Int -> [Int] -> Int
h a b c ts =
    if ts == []
    then 0
    else if head ts == 1
         then (if a > 0
               then h (a-1) b c (tail ts)
               else (if b > 0
                     then h a (b-1) (c+1) (tail ts)
                     else (if c > 0
                           then h a b (c-1) (tail ts)
                           else 1 + h a b c (tail ts))))   --Each bracket () contains *one* value
         else -- i.e. else if head ts == 2
              if b > 0
              then h a (b-1) c (tail ts)
              else 2 + h a b c (tail ts)

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = print . solve . map read . words =<< getContents

solve (n:a_:b_:ts_) = ans where
    ans = if n /= length ts_ then -1 else go 0 a_ b_ ts_
    go r _ _ []     = r
    go r 0 0 ts     = r + sum ts
    go r 0 b (1:ts) = go r 1 (b-1) ts
    go r a b (1:ts) = go r (a-1) b ts
    go r a 0 (2:ts) = go (r+2) a 0 ts
    go r a b (2:ts) = go r a (b-1) ts

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = print . solve . map read . tail . words =<< getContents

solve (a:b:ts) = go 0 a b ts where
    go r _ _ []     = r
    go r 0 0 ts     = r + sum ts
    go r 0 b (1:ts) = go r 1 (b-1) ts
    go r a b (1:ts) = go r (a-1) b ts
    go r a 0 (2:ts) = go (r+2) a 0 ts
    go r a b (2:ts) = go r a (b-1) ts

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = print . solve . map read . tail . words =<< getContents

solve (a:b:ts) = go 0 a b ts where
    go r _ _ []     = r
    go r 0 0 (1:ts) = r + sum ts
    go r 0 b (1:ts) = go r 1 (b-1) ts
    go r a b (1:ts) = go r (a-1) b ts
    go r a 0 (2:ts) = go (r+2) a b ts
    go r a b (2:ts) = go r a (b-1) ts

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = print . solve . map read . tail . words =<< getContents

solve (a_:b_:ts_) = go 0 a_ b_ ts_ where
    go r _ _ []     = r
    go r 0 0 (p:ts) = go (r+p) 0 0 ts
    go r 0 b (1:ts) = go r 1 (b-1) ts
    go r a b (1:ts) = go r (a-1) b ts
    go r a 0 (2:ts) = go (r+2) a 0 ts
    go r a b (2:ts) = go r a (b-1) ts

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = print . solve . map read . tail . words =<< getContents

solve (a:b:ts) = go 0 a b ts where
    go r _ _ []     = r
    go r 0 0 (1:ts) = r + 1 + sum ts
    go r 0 b (1:ts) = go r 1 (b-1) ts
    go r a b (1:ts) = go r (a-1) b ts
    go r a 0 (2:ts) = go (r+2) a b ts
    go r a b (2:ts) = go r a (b-1) ts

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = print . solve . map read . tail . words =<< getContents

solve (a_:b_:ts_) = go 0 a_ b_ ts_ where
    go r _ _ []     = r
    go r 0 0 ts     = r + sum ts
    go r 0 b (1:ts) = go r 1 (b-1) ts
    go r a b (1:ts) = go r (a-1) b ts
    go r a 0 (2:ts) = go (r+2) a 0 ts
    go r a b (2:ts) = go r a (b-1) ts


import Control.Monad
-- import Data.List.HT      (mapAdjacent)

mapAdjacent :: (a -> a -> b) -> [a] -> [b]
mapAdjacent f xs = zipWith f xs (tail xs)

solve :: String -> String
solve s
    | c + 1 == length s = "NO"
    | otherwise         = "YES\n" ++ show (c+1) ++ " " ++ show (c+2)
        where c = length $ takeWhile (==False) $ mapAdjacent (>) s

main :: IO ()
main = do
    _ <- getLine
    s <- getLine
    putStrLn $ solve s

import Data.Maybe
main :: IO ()
main = do
  _ <- getLine
  s <- getLine
  case solve s of
    Nothing -> putStrLn "NO"
    Just i -> do
      putStrLn "YES"
      putStrLn $ (unwords.map show) [i,i+1]

solve :: String -> Maybe Int
solve s = (\(_,_,c) -> c) <$> m
  where m = listToMaybe $ filter (\(x,y,_) -> x>y) $ zip3 s (tail s) [(1::Int)..]

main = getLine >> getLine >>= answer

answer xs
    | n == 0 = putStrLn "NO"
    | otherwise = putStrLn $ "YES\n" ++ show n ++ " " ++ (show $ n + 1)
    where n = solve 0 (pred 'a') xs

solve _ _ [] = 0
solve n c (x:xs) = if c <= x then solve (n+1) x xs else n

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

main = do
	getLine
	s <- getLine
	let
		res = solve ( 1 :: Int ) s
	case res of
		Nothing -> putStrLn "NO"
		Just res -> do
			putStrLn "YES"
			printf "%d %d\n" res $ succ res

solve _ [] = Nothing
solve _ [_] = Nothing
solve pos (a:b:s)
	| a > b = Just pos
	| otherwise = solve ( succ pos ) (b:s)

import Data.List

main :: IO ()
main = do
    n <- getLine
    s <- getLine
    putStrLn $ f2 $ h (f s) s
    return ()
{-
f :: String -> Maybe Int
f s =let r = reverse s in
     elemIndex True $ map (\x -> (compare x s)==LT) (tails r)

c :: Int -> Maybe Int -> String
c n (Just x) ="YES\n"++(show (n-x))++" "++(show n)
c n Nothing = "NO"
-}
f :: String -> Maybe Char
f (x:y:ys) =if x>y then Just (x) else f (y:ys)
f (y:ys) = Nothing

h :: Maybe Char -> String -> Maybe Int
h Nothing _ = Nothing
h (Just x) s = elemIndex x s

f2 :: Maybe Int -> String
f2 Nothing = "NO"
f2 (Just (x)) = "YES\n"++(show x)++" "++(show (x+1))

import Data.List

main :: IO ()
main = do
    n <- getLine
    s <- getLine
    putStrLn $ f2 $ h (f s) s
    return ()
{-
f :: String -> Maybe Int
f s =let r = reverse s in
     elemIndex True $ map (\x -> (compare x s)==LT) (tails r)

c :: Int -> Maybe Int -> String
c n (Just x) ="YES\n"++(show (n-x))++" "++(show n)
c n Nothing = "NO"
-}
f :: String -> Maybe Char
f (x:y:ys) =if x>y then Just (x) else f (y:ys)
f (y:ys) = Nothing

h :: Maybe Char -> String -> Maybe Int
h Nothing _ = Nothing
h (Just x) s = elemIndex x s

f2 :: Maybe Int -> String
f2 Nothing = "NO"
f2 (Just (x)) = "YES\n"++(show (x+1))++" "++(show (x+1+1))

import Control.Monad
-- import Data.List.HT (mapAdjacent)

mapAdjacent :: (a -> a -> b) -> [a] -> [b]
mapAdjacent f xs = zipWith f xs (tail xs)

solve :: String -> String
solve s
    | c + 1 == length s = "NO"
    | otherwise         = "YES\n" ++ show (c+1) ++ " " ++ show (c+2)
        where c = length $ takeWhile (==False) $ mapAdjacent (>) s

main :: IO ()
main = do
    s <- getLine
    putStrLn $ solve s


import Control.Monad
import Data.Array.IO.Safe
import Data.Array.Unboxed
import Data.List
import qualified Data.IntSet as IntSet
import qualified Data.Map.Strict as M

input :: Read a => IO [a]
input = map read <$> words <$> getLine

output :: Show a => [a] -> IO ()
output = putStrLn <$> unwords <$> map show

c n k = product [n-k+1..n] `div` product [1..k]

_mod = 1000000007

main = do
  [t] <- input
  replicateM_ t $ do
    [n] <- input
    a <- input
    let suffixSums = listArray (1, n+1) $ scanr (+) 0 a :: UArray Int Int
    good <- newArray (1, n) False :: IO (IOUArray Int Bool)
    forM_ [1..n+1] $ \i -> forM_ [i+2..n+1] $ \j -> do
      let d = suffixSums!i - suffixSums!j
      if d <= n then writeArray good d True else return ()
    good' <- freeze good :: IO (UArray Int Bool)
    print $ length $ filter (good'!) a

import qualified Data.IntSet as IS
import Data.IntSet (IntSet)

subSums :: Int -> [Int] -> IntSet
--subSums n (a1:a2:as) = IS.union (prefixSums n a1 (a2:as)) $ subSums n (a2:as)
subSums _ [_] = IS.empty
subSums n as = IS.unions $ suffixLists as
    where
        suffixLists [_] = []
        suffixLists lst = getPSums lst:suffixLists (tail lst)
        getPSums (l:ls) = IS.fromDistinctAscList $ prefixSums n l ls

prefixSums :: Int -> Int -> [Int] -> [Int]
prefixSums n offset [] = []
prefixSums n offset (a:as)
    | (offset+a) <= n = (offset+a) : prefixSums n (offset+a) as
    | otherwise     = []

solve :: [Int] -> Int
solve as = length $ filter (`IS.member` sums) as
    where sums = subSums (length as) as

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- getLine
    as <- readNums
    print $ solve as
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readNums
    testCases t

readNums :: (Read n) => IO [n]
readNums = map read . words <$> getLine

import qualified Data.IntSet as IS
import Data.IntSet (IntSet)

subSums :: Int -> [Int] -> IntSet
--subSums n (a1:a2:as) = IS.union (prefixSums n a1 (a2:as)) $ subSums n (a2:as)
subSums _ [_] = IS.empty
subSums n as = IS.unions $ suffixLists as
    where
        suffixLists [_] = []
        suffixLists lst = getPSums lst:suffixLists (tail lst)
        getPSums (l:ls) = IS.fromDistinctAscList $ reverse $ prefixSums n l ls

prefixSums :: Int -> Int -> [Int] -> [Int]
prefixSums n offset [] = [0]
prefixSums n offset (a:as)
    | (offset+a) <= n = (offset+a) : prefixSums n (offset+a) as
    | otherwise     = []

solve :: [Int] -> Int
solve as = length $ filter (`IS.member` sums) as
    where sums = subSums (length as) as

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- getLine
    as <- readNums
    print $ solve as
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readNums
    testCases t

readNums :: (Read n) => IO [n]
readNums = map read . words <$> getLine


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

f k n s | k - 1 > n - k = (concat $ replicate (n - k) "RIGHT\n") ++ g (reverse s) "LEFT\n"
        | otherwise = (concat $ replicate (k - 1) "LEFT\n") ++ g s "RIGHT\n"
        where g [s] _ = ("PRINT " ++ [s] ++ "\n")
              g (s:xs) phrase = ("PRINT " ++ [s] ++ "\n") ++ phrase ++ g xs phrase

main = do
    s <- getLine
    let [n, k] = strToList s
    t <- getLine
    putStrLn $ f k n t

import Control.Applicative

step1 n k s
	| k == 0 = forward n k s
	| k == n - 1 = backward n k s
	| k + k < n = "LEFT\n" ++ step1 n (k - 1) s
	| otherwise = "RIGHT\n" ++ step1 n (k + 1) s

forward n k s
	| k == n - 1 = "PRINT " ++ [s !! k] ++ "\n"
	| otherwise = "PRINT " ++ [s !! k] ++ "\nRIGHT\n" ++ forward n (k + 1) s

backward n k s
	| k == 0 = "PRINT " ++ [s !! k] ++ "\n"
	| otherwise = "PRINT " ++ [s !! k] ++ "\nLEFT\n" ++ backward n (k - 1) s

main = do
	[n, k] <- map read . words <$> getLine
	s <- getLine
	putStr $ step1 n (k - 1) s


{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Bool
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Debug.Trace

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

data TC = TC {n :: Int, l :: Int, r :: Int, k :: Int, as :: [Int]}

type Output = Int

input :: Scanner TC
input = do
  n <- int
  l <- int
  r <- int
  k <- int
  as <- n >< int
  return TC {..}

solve :: TC -> Output
solve TC {..} =
  length
    . takeWhile (<= k)
    . scanl1 (+)
    . filter (>= l)
    . filter (<= r)
    . sort
    $ as

output :: Output -> C.ByteString
output = showB

-------------------------- Template ------------------------------------------
-- Debug
debug :: Show a => a -> a
#ifdef ONLINE_JUDGE
debug = id
#else
debug a = trace (show a) a
#endif

-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts

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

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

-- Scanner
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

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

str :: Scanner String
str = C.unpack <$> bstr

readStr :: Read a => Scanner a
readStr = read <$> str

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show

module Main where

import Data.List(sort, findIndices)

(|>) = flip ($)

-- why does CF not have Data.List.Split??
chunksOf :: Int -> [a] -> [[a]]
chunksOf n [] = []
chunksOf n xs = (take n xs) : (chunksOf n $ drop n xs)

lastOr ::  a -> [a] -> a
lastOr def [] = def
lastOr _def xs = last xs

between :: Integer -> Integer -> [Integer] -> [Integer]
between l r =
    filter (<= r)
    . filter (>= l)

solve :: [[Integer]] -> Int
solve [[n, l, r, k], values] =
    values
    |> between l r
    |> sort
    |> scanl1 (+)
    |> filter (<= k)
    |> length

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

import Data.List

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

batch :: [a] -> [(a, a)]
batch [] = []
batch (a:b:cs) = (a, b) : batch cs

input :: (String, String) -> (Int, Int, Int, Int, [Int])
input (i, j) = let [n, l, r, k] = map read $ words i
                   as = map read $ words j
               in (n, l, r, k, as)

solve :: (Int, Int, Int, Int, [Int]) -> Int
solve (n, l, r, k, as) = snd $ foldl' accum (k, 0) $ sort $ filter inPriceRange as
  where
    accum :: (Int, Int) -> Int -> (Int, Int)
    accum (k', b') p
      | p <= k' = (k' - p, succ b')
      | otherwise = (k', b')

    inPriceRange :: Int -> Bool
    inPriceRange p = l <= p && p <= r

{-# OPTIONS_GHC -O2 #-}

import qualified Data.ByteString.Char8 as DBC
import qualified Data.ByteString.Builder as DBB
import qualified Control.Monad as CM
import qualified Data.List as DL
import System.IO

solve :: IO ()
solve = do
  ~[n,l,r,k] <- readv
  xs <- readv
  let
    ys = DL.sort xs
    zs = DL.takeWhile (<=r) $ DL.dropWhile (<l) ys
    us = DL.scanl' (-) k zs
    vs = tail $ DL.takeWhile (>=0) us
    ans = length vs
  print ans

printv :: [Int] -> IO ()
printv xs = DBB.hPutBuilder stdout $ mconcat $  map (\x->DBB.intDec x <> DBB.char8 ' ') xs

readv :: IO [Int]
readv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)

main :: IO ()
main = do
  --hSetBuffering stdout NoBuffering
  ~[nTc] <- readv
  CM.replicateM_ nTc solve

import Data.List
import Control.Monad
main = readLn >>= flip replicateM (
 map read <$> words <$> getLine >>= \(n:l:r:k:_) ->
 map read <$> words <$> getLine >>= \x ->
 print $ length $ takeWhile (<=k) $ scanl1 (+) $ sort $ filter (\i -> (i >= l) && (i <= r)) x)

{-# LANGUAGE RecordWildCards #-}
module Main where

import Data.List (sort)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

toArr :: Read a => String -> [a]
toArr = map read . words

data InType  = In { n :: Integer
                  , l :: Integer
                  , r :: Integer
                  , k :: Integer
                  , a :: [Integer]
                  }
type OutType = Integer

ps :: [Integer] -> [Integer]
ps = go 0
  where go :: Integer -> [Integer] -> [Integer]
        go _ [] = []
        go acc (x : xs) = let acc' = x + acc
                          in acc' : go acc' xs

solve :: InType -> OutType
solve In {..} =
  let av = sort $ filter (\x -> x >= l && x <= r) a
      p  = ps av
  in fromIntegral $ length $ takeWhile (<= k) p

receive :: [String] -> InType
receive [nlrk, sArr] =
  case toArr nlrk of
    [n, l, r, k] -> In n l r k (toArr sArr)
    _            -> error "parse error on input"
receive _ = error "parse error on input"

main :: IO ()
main = interact $ unlines . map (show . solve . receive) . chunksOf 2 . tail . lines


import Data.List

allEqual :: String -> Bool
allEqual s = length (group s) == 1

solve1 :: String -> String
solve1 (s:ss)
    | allEqual (s:ss)       = s:ss
    | otherwise             = solveHelper s (s:ss)

switch :: Char -> Char
switch '1' = '0'
switch '0' = '1'

solveHelper :: Char -> String -> String
solveHelper _ "" = ""
solveHelper c (s:ss)
    | s == c        = s: solveHelper (switch c) ss
    | otherwise     = c: solveHelper (switch c) (s:ss)

solveTestCases :: Int -> IO ()
solveTestCases 0 = return ()
solveTestCases t = do
    s <- getLine
    putStrLn $ solve1 s
    solveTestCases (t-1)

main :: IO ()
main = do
    t <- getLine
    solveTestCases $ read t

module Main where

import Control.Monad
import Data.List
import qualified Data.Set as S

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Integer]
getIntList = map read <$> getStrList

printStrList :: [String] -> IO ()
printStrList = putStrLn . intercalate " "

printList :: (Show a) => [a] -> IO ()
printList = printStrList . map show

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

(-->) :: a -> (a -> b) -> b
(-->) = flip ($)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        s <- getLine
        let n = length s
        putStrLn $ take (2 * n) $ f s

f :: String -> String
f s = case (length . group . sort $ s) of
    1 -> repeat . head $ s
    2 -> cycle "10"

import Control.Monad

main = readLn >>= flip replicateM_ test

test = do
    t <- getLine
    if all (== head t) t
        then putStrLn t
        else putStrLn $ take (2 * length t) (cycle "01")

import qualified Data.List as L

solve :: String -> String
solve s
  | s == (take n $ repeat $ (s!!0)) = s
  | otherwise = concat $ take n $ repeat "01"
  where n = length s

main = interact $ unlines . map solve . tail . lines

import Control.Monad

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

routine :: IO ()
routine = do
  s <-  getLine
  putStrLn $ if all (== head s) s then s else concat $ replicate (length s) "10"

import Control.Monad

main :: IO ()
main = do
  tt <- read <$> getLine
  replicateM_ tt $ do
    t <- getLine
    putStrLn $ if any (=='0') t && any (=='1') t
      then concat $ map (\_ -> "01") t
      else t

import Control.Monad

main :: IO ()
main = do
  tt <- read <$> getLine
  replicateM_ tt $ do
    t <- getLine
    putStrLn $ concat $ map (\_ -> "01") t


import Control.Monad
import Data.Array
import IO

gao n l = elems a where
	a = listArray (1, n) [maximum $ 0:[a!j + s (b!j) (b!i) | j <- [1 .. i - 1]] | i <- [1 .. n]]
	b = listArray (1, n) l
	s [x,a,b] [y,c,d] = min x $ maximum $ 0:[f, g, h] where
		i = (b - a) / x
		j = (d - c) / y
		f = (c - a) / i
		g = if d <= b then (d - a) / i - y else 0
		h = if b <= d then x - (b - c) / j else 0

main = do
	i <- openFile "input.txt" ReadMode
	o <- openFile "output.txt" WriteMode
	n <- fmap read $ hGetLine i
	l <- replicateM n $ fmap (map read . words) $ hGetLine i
	hPutStrLn o $ show $ maximum $ zipWith (+) (map head l) (gao n l)
	hClose i
	hClose o

main = do
  x <- readFile "input.txt"
  writeFile "output.txt" (f x)
f theInput = show answer where
  n:bowl0 = lines theInput
  bowl = reverse $ map (map (read::String->Float)) $ map words bowl0
  height [x] = [(x,0)]
  height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs
  h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)
    | rb1 > rt2 = h2 + h3
    | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3
    | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3
    | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3
  answer = foldl1 max [h1 + h2|([h1,_,_],h2)<-height bowl]

import Array
import Monad (liftM)

(?) :: Bool -> a -> a -> a
(?) True   =  const
(?) False  =  flip const

parse :: Read a => String -> (a, a, a)
parse line  =  case words line of
    [s1, s2, s3]  ->  (read s1, read s2, read s3)

getHeight :: (Int, Int, Int) -> Int
getHeight (h, _, _)  =  h

solve :: Int -> Array Int (Int, Int, Int) -> Double
solve n xs  =  maximum [hs ! i + fromIntegral (getHeight (xs ! i)) | i <- [1..n]]
  where
    hs  =  array (1, n) ((1, 0) :
        [(i, maximum [height (xs ! i) (xs ! j) (hs ! j) | j <- [1..i-1]]) | i <- [2..n]])

    height t1@(h1, a1, b1) t2@(h2, a2, b2) d2
      | a1 >= b2   =  d2 + fromIntegral h2
      | otherwise  =  case compareDelta t1 t2 of
        LT  ->  d2 + max 0 (fromIntegral h2 - fromIntegral (b2 - a1) * tanDelta t1)
        _   ->  (a1 <= a2) ? d2 $ d2 + fromIntegral (a1 - a2) * tanDelta t2

    tanDelta (h, a, b)  =  fromIntegral h / fromIntegral (b - a)
    compareDelta (h1, a1, b1) (h2, a2, b2)  =  compare (h1 * (b2 - a2)) (h2 * (b1 - a1))

main :: IO ()
main  =  do
    ls  <-  liftM lines $ readFile "input.txt"
    let n   =  read $ head ls
    let xs  =  listArray (1,n) $ take n $ map parse $ tail ls
    writeFile "output.txt" $ show $ solve n xs

main = do
  x <- readFile "input.txt"
  writeFile "output.txt" (f x)
f theInput = show answer where
  n:bowl0 = lines theInput
  bowl = reverse $ map (map (read::String->Float)) $ map words bowl0
  height [x] = [(x,0)]
  height (x:xs) = (x,foldl1 max (map (h0 x) ys)):ys where ys = height xs
  h0 [h1,rb1,rt1] ([h2,rb2,rt2],h3)
    | rb1 > rt2 = h2 + h3
    | h1*(rt2-rb2) > h2*(rt1-rb1) = if rb1 < rb2 then h3 else (rb1-rb2)*h2/(rt2-rb2)+h3
    | rt1 < rt2 = max 0 ((rt1-rb2)*h2/(rt2-rb2)-h1) + h3
    | otherwise = max 0 (h2-(rt2-rb1)*h1/(rt1-rb1)) + h3
  answer = h1 + h2 where ([h1,_,_],h2):_ = height bowl


import Control.Monad

solve :: Int -> Int -> [Int] -> Maybe (Int,[[Int]])
solve a b l
  |a/=b || a <3 = Nothing
  | otherwise = Just (2*sum l,[[x,1+mod x a]|x <- [1..a]])

routine :: IO ()
routine = do
  [a,b] <-(map read.words) <$> getLine
  l <- (map read.words) <$> getLine
  case solve a b l of
    Just x -> f x
    _ -> putStrLn "-1"

f :: (Int,[[Int]]) -> IO ()
f (a,l) = do
  print a
  forM_ l (putStrLn . unwords . map show)

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

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad(forM_, liftM, replicateM, replicateM_)
import Data.List(sortBy, intercalate)

-- Input parsing
parseInts :: String -> [Int]
parseInts str = map read (words str)

parseIntsM :: IO [Int]
parseIntsM = parseInts <$> getLine

-- Solution

data Edge = Edge (Int, Int)
type EdgeWithCost = (Edge, Int)

data Solution = Solution {
  cost :: Int,
  edgeCount :: Int,
  edges :: [Edge]
}

data Query = Query {
  vertexCount :: Int,
  edgeLimit :: Int,
  weights :: [Int]
}

data Vertex = Vertex {
  ix :: Int,
  weight :: Int
}

instance Show Edge where
  show (Edge (src, dst)) = show src ++ " " ++ show dst

instance Show Solution where
  show (Solution cost count edges) =
    let edgeString =  intercalate "\n" . map show $ edges in
      show cost ++ "\n" ++ edgeString

mapOrd :: Ord b => (a -> b) -> a -> a -> Ordering
mapOrd f lhs rhs = compare (f lhs) (f rhs)

vertexOrd :: Ord Int => Vertex -> Vertex -> Ordering
vertexOrd = mapOrd weight

x :: Vertex -> Vertex -> EdgeWithCost
x v1 v2 = (Edge (ix v1, ix v2), weight v1 + weight v2)

rotate :: Int -> [a] -> [a]
rotate n l = (drop n l) ++ (take n l)

x2 :: [Vertex] -> [EdgeWithCost]
x2 vs = zipWith x vs (rotate 1 vs)

fridgeSolve :: Query -> Maybe Solution
fridgeSolve q =
  let v = vertexCount q in
    let e = edgeLimit q in
      let dummyEdges = e - v in
        if dummyEdges < 0 || v < 3 then Nothing else
          let s@(v1:v2:rest) :: [Vertex] = sortBy vertexOrd $ zipWith Vertex [1..v] $ weights q in
            let p :: [EdgeWithCost] = (x2 s) ++ (replicate dummyEdges (x v1 v2)) in
              Just $ Solution (foldr (+) 0 $ map snd p) e (map fst p)

taskM :: IO ()
taskM = do
  [n, m] <- parseIntsM
  ws <- parseIntsM
  case (fridgeSolve (Query n m ws)) of
    Nothing -> print $ -1
    Just s -> print $ s

main :: IO ()
main = do
  [t] <- parseIntsM
  replicateM_ t taskM

import Control.Monad

solve :: Int -> Int -> [Int] -> Maybe (Int,[[Int]])
solve a b l
  |a/=b = Nothing
  | otherwise = Just (2*sum l,[[x,1+mod x a]|x <- [1..a]])

routine :: IO ()
routine = do
  [a,b] <-(map read.words) <$> getLine
  l <- (map read.words) <$> getLine
  case solve a b l of
    Just x -> f x
    _ -> putStrLn "-1"

f :: (Int,[[Int]]) -> IO ()
f (a,l) = do
  print a
  forM_ l (\x -> putStrLn $ unwords $ map show x)

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

import Control.Monad

solve :: Int -> Int -> [Int] -> Maybe (Int,[[Int]])
solve a b l
  |a/=b = Nothing
  | otherwise = Just (2*sum l,[[x,mod (x+1) (a+1)]|x <- [1..a]])

routine :: IO ()
routine = do
  [a,b] <-(map read.words) <$> getLine
  l <- (map read.words) <$> getLine
  case solve a b l of
    Just x -> f x
    _ -> putStrLn "-1"

f :: (Int,[[Int]]) -> IO ()
f (a,l) = do
  print a
  forM_ l (\x -> putStrLn $ unwords $ map show x)

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


solve [s1, s2] =
  let [_,k] = map read $ words $ s1 :: [Integer]
      update ('a':_) (a,b) d = (a + d, b)
      update ('b':_) (a,b) d = (a, b + d)
      helper x y (a, b) res
          | min a b > k = helper (tail x) y (update x (a, b) (-1)) res
          | y == [] = max (a + b) res
          | otherwise = helper x (tail y) (update y (a, b) 1) (max res (a + b))
  in helper s2 s2 (0, 0) 0
main = getContents >>= putStrLn . show . solve . lines

solve s =
  let [s1,s2] = lines s
      [_,k] = map read $ words $ s1 :: [Integer]
      update ('a':_) (a,b) d = (a + d, b)
      update ('b':_) (a,b) d = (a, b + d)
      helper x y (a, b) dis res
          | min a b > k = helper (tail x) y (update x (a, b) (-1)) (dis - 1) res
          | y == [] = max dis res
          | otherwise = helper x (tail y) (update y (a, b) 1) (dis + 1) (max res dis)
  in helper s2 s2 (0, 0) 0 0
main :: IO()
main = getContents >>= putStrLn . show . solve

import Data.List
import Data.Functor

main :: IO()
main = do
    [_, k] <- map read . words <$> getLine
    s <- getLine
    print $ maximum $ map (\x -> solve (== x) s k) "ab"

solve :: (Char -> Bool) -> String -> Int -> Int
solve f s k = solve' s s 0 0
    where solve' :: String -> String -> Int -> Int -> Int
          solve' []     []     _   _   = 0
          solve' []     (t:ts) cnt len | cnt <= k  = len
                                       | f t       = solve' [] ts cnt (len - 1)
                                       | otherwise = solve' [] ts (cnt - 1) (len - 1)
          solve' (h:hs) (t:ts) cnt len | cnt <= k  = max len (solve' hs (t:ts) (cnt + if f h then 0 else 1) (len + 1))
                                       | otherwise = solve' (h:hs) ts (cnt - if f t then 0 else 1) (len - 1)

pp = putStrLn

aaa (a : bb) (c : dd)  k used len mx
  | a == 'a' =
    aaa bb (c : dd) k used (succ len) (maximum [(succ len), mx])
  | a == 'b' && used < k =
    aaa bb (c : dd) k (succ used) (succ len) (maximum [(succ len),mx])
  | a == 'b' && used == k && c == 'b' =
    aaa (a : bb) dd k (pred used) (pred len) mx
  | a == 'b' && used == k && c == 'a' =
    aaa (a : bb) dd k used (pred len) mx
aaa mpt something k used len mx = mx

invert (a : bb)
 | a == 'a' = 'b' : (invert bb)
 | a == 'b' = 'a' : (invert bb)
invert mpt = []

-- do one pass for a and one for b
main = do
  fff <- getLine
  let nnn = (read (head (words fff)))::Int
      kkk = (read (last (words fff)))::Int

  gg <- getLine

  let one = aaa gg gg kkk 0 0 0
      two = aaa (invert gg) (invert gg) kkk 0 0 0

  pp (show (maximum [one,two]))

pp = putStrLn

aaa (a : bb) (c : dd)  k used len mx
  | a == 'a' =
    aaa bb (c : dd) k used (succ len) (maximum [(succ len), mx])
  | a == 'b' && used < k =
    aaa bb (c : dd) k (succ used) (succ len) (maximum [(succ len),mx])
  | a == 'b' && used == k && c == 'b' =
    aaa (a : bb) dd k (pred used) (pred len) mx
  | a == 'b' && used == k && c == 'a' =
    aaa (a : bb) dd k used (pred len) mx
aaa mpt something k used len mx = mx

invert (a : bb)
 | a == 'a' = 'b' : (invert bb)
 | a == 'b' = 'a' : (invert bb)
invert mpt = []

-- do one pass for a and one for b
main = do
  ff <- getLine
  let n = (read (head (words ff)))::Int
      k = (read (last (words ff)))::Int

  gg <- getLine

  let one = aaa gg gg k 0 0 0
      two = aaa (invert gg) (invert gg) k 0 0 0

  pp (show (maximum [one,two]))

import Data.List
import Control.Applicative

_distList :: Char -> [Int] -> [Int]
_distList 'a' (x:xs) = (x+1):xs
_distList 'b' xs = 0:xs

distList :: String -> [Int]
distList = foldr _distList [0]

partialSums :: Int -> [Int] -> [Int]
partialSums sz lst =
    zipWith (-) (drop sz initsSums) initsSums
        where initsSums = 0:(scanl1 (+) lst)

solve :: Int -> String -> Int
solve k str =
    let dList = distList str in
        case partialSums (k+1) dList of
            [] -> sum [length dList, (-1), sum dList]
            pSums -> (k+) . maximum $ pSums

main :: IO()
main = do
    k <- (read . (!!1) . words) <$> getLine
    s <- getLine
    print . maximum $
        [solve k] <*> (
            [id, map (\x -> case x of {'a' -> 'b'; 'b' -> 'a'})] <*> [s]
        )