{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM_ )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( unfoldr )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue m x = (let V1 (V1 p) = (helper x !*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q) where helper = adjoint . fmap V1

-- eigenvalues m = go [] m
--   where
--     c0 = eigenvector m
--     e0 = eigenvalue m c0
--     go acc ma | isNaN ev  = acc
--               | otherwise = go (ev : acc) ma'
--       where
--         ec  = eigenvector ma
--         ev  = eigenvalue ma ec
--         ec' = (<$ zero) <$> ec
--         ma' = ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec)

{-

>>> mt = V2 (V2 1 2) (V2 3 4)
>>> ev = eigenvector mt
>>> el = eigenvalue mt ev

>>> ev
V2 0.41597355791928425 0.9093767091321241

>>> el
5.372281323269014

>>> el *!! identity :: M22 Double
V2 (V2 5.372281323269014 0.0) (V2 0.0 5.372281323269014)

>>> (mt - el *!! identity)
V2 (V2 (-4.372281323269014) 2.0) (V2 3.0 (-1.3722813232690143))

>>> luFinite (mt - el *!! identity)
(V2 (V2 (-4.372281323269014) 0.0) (V2 3.0 0.0),V2 (V2 1.0 (-0.4574271077563381)) (V2 0.0 NaN))

>>> luDetFinite (mt - el *!! identity)
NaN

>>> eigenvalues mt
[-0.37228132326901475,5.372281323269014]

>>> m3 = V3 (V3 1 2 3) (V3 4 5 6) (V3 7 8 9)

>>> eigenvalues m3
[-1.1168439698070434,16.116843969807043]

>>> m4 = V4 (V4 1 2 3 4) (V4 5 6 7 8) (V4 9 10 11 12) (V4 13 14 15 16)

>>> eigenvalues m4
[-2.2093727122985376,36.20937271229855]

>>> m5 = fromJust $ fromVector @5 (fromJust . fromVector @5 <$> (fromList <$> fromList [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]))

>>> m5
V {toVector = [V {toVector = [1,2,3,4,5]},V {toVector = [6,7,8,9,10]},V {toVector = [11,12,13,14,15]},V {toVector = [16,17,18,19,20]},V {toVector = [21,22,23,24,25]}]}

>>> eigenvalues m5
[-3.64208073700242,68.6420807370024]

>>> lx = V3 (V2 1 2) (V2 3 4) (V2 5 6)

>>> eigenvalues (lx !*! adjoint lx)
[0.264505087265819,90.73549491273418]

-}

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, y] <- readChar8'
        case (x > y, x == y) of
            (True, _   ) -> print (x + y)
            (_   , True) -> print x
            _            -> print $ y - (y `mod` x) `div` 2

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

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

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[x, y] <- getInts 2
    pure $ putInts $ pure $ case  divMod y x  of
      (0, _) -> x + y
      (_, r) -> y - div r 2

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM_ )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( unfoldr )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue m x = (let V1 (V1 p) = (helper x !*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q) where helper = adjoint . fmap V1

-- eigenvalues m = go [] m
--   where
--     c0 = eigenvector m
--     e0 = eigenvalue m c0
--     go acc ma | isNaN ev  = acc
--               | otherwise = go (ev : acc) ma'
--       where
--         ec  = eigenvector ma
--         ev  = eigenvalue ma ec
--         ec' = (<$ zero) <$> ec
--         ma' = ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec)

{-

>>> mt = V2 (V2 1 2) (V2 3 4)
>>> ev = eigenvector mt
>>> el = eigenvalue mt ev

>>> ev
V2 0.41597355791928425 0.9093767091321241

>>> el
5.372281323269014

>>> el *!! identity :: M22 Double
V2 (V2 5.372281323269014 0.0) (V2 0.0 5.372281323269014)

>>> (mt - el *!! identity)
V2 (V2 (-4.372281323269014) 2.0) (V2 3.0 (-1.3722813232690143))

>>> luFinite (mt - el *!! identity)
(V2 (V2 (-4.372281323269014) 0.0) (V2 3.0 0.0),V2 (V2 1.0 (-0.4574271077563381)) (V2 0.0 NaN))

>>> luDetFinite (mt - el *!! identity)
NaN

>>> eigenvalues mt
[-0.37228132326901475,5.372281323269014]

>>> m3 = V3 (V3 1 2 3) (V3 4 5 6) (V3 7 8 9)

>>> eigenvalues m3
[-1.1168439698070434,16.116843969807043]

>>> m4 = V4 (V4 1 2 3 4) (V4 5 6 7 8) (V4 9 10 11 12) (V4 13 14 15 16)

>>> eigenvalues m4
[-2.2093727122985376,36.20937271229855]

>>> m5 = fromJust $ fromVector @5 (fromJust . fromVector @5 <$> (fromList <$> fromList [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]))

>>> m5
V {toVector = [V {toVector = [1,2,3,4,5]},V {toVector = [6,7,8,9,10]},V {toVector = [11,12,13,14,15]},V {toVector = [16,17,18,19,20]},V {toVector = [21,22,23,24,25]}]}

>>> eigenvalues m5
[-3.64208073700242,68.6420807370024]

>>> lx = V3 (V2 1 2) (V2 3 4) (V2 5 6)

>>> eigenvalues (lx !*! adjoint lx)
[0.264505087265819,90.73549491273418]

-}

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, y] <- readChar8'
        case (x > y, x == y) of
            (True, _   ) -> print (x + y)
            (_   , True) -> print x
            _            -> if even (x + y) then print $ (x + y) `div` 2 else print $ (x + y + if odd x then x else y) `div` 2

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM_ )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( unfoldr )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue m x = (let V1 (V1 p) = (helper x !*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q) where helper = adjoint . fmap V1

-- eigenvalues m = go [] m
--   where
--     c0 = eigenvector m
--     e0 = eigenvalue m c0
--     go acc ma | isNaN ev  = acc
--               | otherwise = go (ev : acc) ma'
--       where
--         ec  = eigenvector ma
--         ev  = eigenvalue ma ec
--         ec' = (<$ zero) <$> ec
--         ma' = ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec)

{-

>>> mt = V2 (V2 1 2) (V2 3 4)
>>> ev = eigenvector mt
>>> el = eigenvalue mt ev

>>> ev
V2 0.41597355791928425 0.9093767091321241

>>> el
5.372281323269014

>>> el *!! identity :: M22 Double
V2 (V2 5.372281323269014 0.0) (V2 0.0 5.372281323269014)

>>> (mt - el *!! identity)
V2 (V2 (-4.372281323269014) 2.0) (V2 3.0 (-1.3722813232690143))

>>> luFinite (mt - el *!! identity)
(V2 (V2 (-4.372281323269014) 0.0) (V2 3.0 0.0),V2 (V2 1.0 (-0.4574271077563381)) (V2 0.0 NaN))

>>> luDetFinite (mt - el *!! identity)
NaN

>>> eigenvalues mt
[-0.37228132326901475,5.372281323269014]

>>> m3 = V3 (V3 1 2 3) (V3 4 5 6) (V3 7 8 9)

>>> eigenvalues m3
[-1.1168439698070434,16.116843969807043]

>>> m4 = V4 (V4 1 2 3 4) (V4 5 6 7 8) (V4 9 10 11 12) (V4 13 14 15 16)

>>> eigenvalues m4
[-2.2093727122985376,36.20937271229855]

>>> m5 = fromJust $ fromVector @5 (fromJust . fromVector @5 <$> (fromList <$> fromList [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]))

>>> m5
V {toVector = [V {toVector = [1,2,3,4,5]},V {toVector = [6,7,8,9,10]},V {toVector = [11,12,13,14,15]},V {toVector = [16,17,18,19,20]},V {toVector = [21,22,23,24,25]}]}

>>> eigenvalues m5
[-3.64208073700242,68.6420807370024]

>>> lx = V3 (V2 1 2) (V2 3 4) (V2 5 6)

>>> eigenvalues (lx !*! adjoint lx)
[0.264505087265819,90.73549491273418]

-}

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, y] <- readChar8'
        case (x < y, x == y) of
            (True, _   ) -> print (x + y)
            (_   , True) -> print x
            _            -> if even (x + y) then print $ (x + y) `div` 2 else print $ (x + y + if odd x then x else y) `div` 2

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

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

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[x, y] <- getInts 2
    pure $ putInts $ pure $ if  x > y
      then  x + y
      else  quot (x + y) 2

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp


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

gao a = 4 + sum [maximum (map f a) | f <- [sum, foldl1 (-), foldl1 subtract, negate . sum]]
main = do C.interact $ C.pack . show . gao . map (map (fst . fromJust . C.readInt) . C.words) . tail . C.lines

{-
	2 * (max{x} - min{x})
	2 * (max{y} - min{y})
	-|max{x} + max{y} - max{x + y}|
	-|min{x + y} - min{x} - min{y}|
	-|max{x} - min{y} - max{x - y}|
	-|max{y} - min{x} - max{y - x}|
=	max{x+y}+max{x-y}+max{y-x}+max{-x-y}
-}-}
{-
# 	When 	Who 	Problem 	Lang 	Verdict 	Time 	Memory
229404 	Dec 24, 2010 11:07:18 AM 	watashi 	C - Happy Farm 5 	Haskell 	Time limit exceeded on test 69 	2000 ms 	14888 KB
-}


{-# OPTIONS_GHC -funbox-strict-fields #-}

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

type Pos = (Int, Int, Int, Int)

conv :: [Int] -> Pos
conv [x1, y1, x2, y2] = (x1, y1, x2, y2)
conv _            = error "conv: Invalid format"

divide :: Pos -> Pos -> [Pos]
divide this@(x1, y1, x2, y2) byThat@(x1', y1', x2', y2')
  | x1' == x2' && x1 < x1' && x1' < x2 && y1 == y1' && y2 == y2'= do
      [(x1, y1, x1', y2), (x1', y1, x2, y2)]
  | y1' == y2' && y1 < y1' && y1' < y2 && x1 == x1' && x2 == x2'= do
      [(x1, y1, x2, y1'), (x1, y1', x2, y2)]
  | otherwise  = []

calcArea :: Pos -> Int
calcArea (x1, y1, x2, y2) = (x2 - x1) * (y2 - y1)

findBreak cs bs = head $ do
  c <- cs
  b <- bs
  case divide c b of
    _ :_ -> [(c, b)]
    _    -> []

main :: IO ()
main = do
  let readInts = map read . words :: String -> [Int]
  w : h : n : _ <- readInts <$> getLine
  breaks <- replicateM n $ conv . readInts <$> getLine
  let chocolate = (0, 0, w, h)
      findBreak cs bs = head $ do
        c <- cs
        b <- bs
        case divide c b of
          _ :_ -> [(c, b)]
          _    -> []
      bob'sJob cs [] = cs
      bob'sJob cs bs = do
        let (c, b) = findBreak cs bs
        bob'sJob (delete c cs ++ (divide c b)) (delete b bs)
      answer = sort . map calcArea $ bob'sJob [chocolate] breaks
  putStrLn . intercalate " " $ map show answer

import Control.Monad
import Data.List

getA = fmap (map read . words) getLine

main = do
	[w,h,n] <- getA
	a <- replicateM n getA
	putStr $ unwords $ map show $ sort $ gao [0,0,w,h] a

gao [x1,y1,x2,y2] [] = [(x2 - x1) * (y2 - y1)]
gao [x1,y1,x2,y2] a = gao r p ++ gao s q where
	c@[x3,y3,x4,y4] = head $ filter (\[i,j,k,l] -> (i==x1 && k==x2) || (j==y1 && l==y2)) a
	(r@[x5,y5,x6,y6],s) = if x3==x4 then ([x1,y1,x3,y2],[x3,y1,x2,y2]) else ([x1,y1,x2,y3],[x1,y3,x2,y2])
	(p,q) = partition (\[i,j,k,l] -> x5<=i && y5<=j && k<=x6 && l<=y6) $ delete c a

{-# OPTIONS_GHC -funbox-strict-fields #-}

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

type Pos = (Int, Int, Int, Int)

conv :: [Int] -> Pos
conv [x1, y1, x2, y2] = (x1, y1, x2, y2)
conv _            = error "conv: Invalid format"

divide :: Pos -> Pos -> Maybe [Pos]
divide this@(x1, y1, x2, y2) byThat@(x1', y1', x2', y2')
  | x1' == x2' && x1 < x1' && x1' < x2 && y1 == y1' && y2 == y2'= do
      Just $ [(x1, y1, x1', y2), (x1', y1, x2, y2)]
  | y1' == y2' && y1 < y1' && y1' < y2 && x1 == x1' && x2 == x2'= do
      Just $ [(x1, y1, x2, y1'), (x1, y1', x2, y2)]
  | otherwise  = Nothing

calcArea :: Pos -> Int
calcArea (x1, y1, x2, y2) = (x2 - x1) * (y2 - y1)

main :: IO ()
main = do
  let readInts = map read . words :: String -> [Int]
  w : h : n : _ <- readInts <$> getLine
  breaks <- replicateM n $ conv . readInts <$> getLine
  let chocolate = (0, 0, w, h)
      bob'sJob parts b = do
        let check p1 p2 = maybe [p1] id $ divide p1 p2
        concat $ map (`check` b) parts
      answer = sort . map calcArea $ foldl bob'sJob [chocolate] breaks
  putStrLn . intercalate " " $ map show answer


main = interact foo

type Point = (Int, Int)
type Line = [Point]

foo :: String -> String
foo inp =
    let points = zip [1..] . map read . words . (!! 1) . lines $ inp :: [Point]
    in if mlines points [] []
        then "Yes"
        else "No"

baz :: Point -> Point -> Double
baz p1 p2 =
    let (x1, y1) = p1
        (x2, y2) = p2
    in (fromIntegral $ y1 - y2) / (fromIntegral $ x1 - x2)

k :: Double -> Point -> Double
k b (x, y) = (fromIntegral y) - b * (fromIntegral x)

check :: Line -> Line -> Bool
check [] _ = False
check _ [] = False
check l [p] = not $ compatible l p
check [p] l = check l [p]
check ps1 ps2 =
    let p11 = head ps1
        p21 = ps1 !! 1
        p12 = ps2 !! 0
        p22 = ps2 !! 1
        b1 = baz p11 p21
        b2 = baz p12 p22
    in if b1 == b2
        then if k b1 p11 == k b2 p12
            then False
            else True
        else False

compatible :: Line -> Point -> Bool
compatible [] _ = True
compatible [_] _ = True
compatible l p =
    let p1 = head l
    in baz p1 p == baz (l !! 0) (l !! 1)

mlines :: [Point] -> Line -> Line -> Bool
mlines [] l1 l2 = check l1 l2
mlines (p:ps) l1 l2 =
    let c1 = compatible l1 p
        c2 = compatible l2 p
        per :: Point -> Bool
        per pp =
            if mlines ps (pp:l1) l2
                then True
                else mlines ps l1 (pp:l2)
    in if validate l1 l2
        then
            if c1 && c2
                then if length l1 < 2 || length l2 < 2
                    then per p
                    else False
                else if c1
                    then mlines ps (p:l1) l2
                    else if c2
                        then mlines ps l1 (p:l2)
                        else False
        else False

validate :: Line -> Line -> Bool
validate [] _ = True
validate _ [] = True
validate [_] [_] = True
validate l1 l2 = check l1 l2

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import Data.Int (Int64)

data Pnt = Pnt (Int64, Int64) deriving Eq

parallel (Pnt (x1, y1)) (Pnt (x2, y2)) (Pnt (x3, y3)) (Pnt (x4, y4))
    | (y2 - y1) * (x4 - x3) == (y4 - y3) * (x2 - x1) = True | otherwise = False

divide p1 p2 [] b = b
divide p1 p2 (px:xs) b | parallel p1 p2 p1 px = divide p1 p2 xs b
                       | otherwise = divide p1 p2 xs (px:b)

test xs p1 p2 | length d == 0 = False | length d == 1 = True
              | otherwise = let (dx:dy:ds) = d in parallel p1 p2 dx dy && divide dx dy ds [] == []
    where d = divide p1 p2 xs []

run (x:y:z:xs) | divide y z (x:xs) [] == [x] = True | otherwise = any (test (y:z:xs) x) (y:z:xs)

main :: IO ()
main = do
    _ <- getLine
    (map Pnt . zip [1..] . map (read :: String -> Int64) . words -> xs) <- getLine
    putStrLn $ case run xs of
        True  -> "Yes"
        False -> "No"

main = interact foo

type Point = (Int, Int)
type Line = [Point]

foo :: String -> String
foo inp =
    let points = zip [1..] . map read . words . (!! 1) . lines $ inp :: [Point]
    in if mlines points [] []
        then "Yes"
        else "No"

baz :: Point -> Point -> Double
baz p1 p2 =
    let (x1, y1) = p1
        (x2, y2) = p2
    in (fromIntegral $ y1 - y2) / (fromIntegral $ x1 - x2)

k :: Double -> Point -> Double
k b (x, y) = (fromIntegral y) - b * (fromIntegral x)

check :: Line -> Line -> Bool
check [] _ = False
check _ [] = False
check l [p] = not $ compatible l p
check [p] l = check l [p]
check ps1 ps2 =
    let p11 = head ps1
        p21 = ps1 !! 1
        p12 = ps2 !! 0
        p22 = ps2 !! 1
        b1 = baz p11 p21
        b2 = baz p12 p22
    in if b1 == b2
        then if k b1 p11 == k b2 p12
            then False
            else True
        else False

compatible :: Line -> Point -> Bool
compatible [] _ = True
compatible [_] _ = True
compatible l p =
    let p1 = head l
    in baz p1 p == baz (l !! 0) (l !! 1)

mlines :: [Point] -> Line -> Line -> Bool
mlines [] l1 l2 = check l1 l2
mlines _ l1 l2 | not $ validate l1 l2 = False
mlines (p:ps) l1 l2 =
    let c1 = compatible l1 p
        c2 = compatible l2 p
        per :: Point -> Bool
        per pp =
            if mlines ps (pp:l1) l2
                then True
                else mlines ps l1 (pp:l2)
    in
        if c1 && c2
            then if length l1 < 2 || length l2 < 2
                then per p
                else False
            else if c1
                then mlines ps (p:l1) l2
                else if c2
                    then mlines ps l1 (p:l2)
                    else False

validate :: Line -> Line -> Bool
validate [] _ = True
validate _ [] = True
validate [_] [_] = True
validate l1 l2 = check l1 l2

main = interact foo

type Point = (Int, Int)
type Line = [Point]

foo :: String -> String
foo inp =
    let points = zip [1..] . map read . words . (!! 1) . lines $ inp :: [Point]
    in if mlines points [] []
        then "Yes"
        else "No"

baz :: Point -> Point -> Double
baz p1 p2 =
    let (x1, y1) = p1
        (x2, y2) = p2
    in (fromIntegral $ y1 - y2) / (fromIntegral $ x1 - x2)

k :: Double -> Point -> Double
-- k a b | trace ("k " ++ show a ++ " " ++ show b) False = undefined
k b (x, y) = (fromIntegral y) - b * (fromIntegral x)

check :: Line -> Line -> Bool
-- check l1 l2 | trace ("check " ++ show l1 ++ " " ++ show l2) False = undefined
check [] _ = False
check _ [] = False
check [p] l = check l [p]
check l [p] = not $ compatible l p
check ps1 ps2 =
    let p11 = head ps1
        p21 = ps1 !! 1
        p12 = ps2 !! 0
        p22 = ps2 !! 1
        b1 = baz p11 p21
        b2 = baz p12 p22
    in if b1 == b2
        then if k b1 p11 == k b2 p12
            then False
            else True
        else False

compatible :: Line -> Point -> Bool
-- compatible l p | trace ("compatible " ++ show l ++ " " ++ show p) False = undefined
compatible [] _ = True
compatible [_] _ = True
compatible l p =
    let p1 = head l
    in baz p1 p == baz (l !! 0) (l !! 1)

mlines :: [Point] -> Line -> Line -> Bool
-- mlines a b c | trace ("mlines " ++ show a ++ " " ++ show b ++ " " ++ show c) False = undefined
mlines [] l1 l2 = check l1 l2
-- mlines ps [] [] = mlines (drop 4 ps) (take 2 ps) (take 2 . drop 2 $ ps)
mlines (p:ps) l1 l2 =
    let c1 = compatible l1 p
        c2 = compatible l2 p
        per :: Point -> Bool
        per pp =
            if mlines ps (pp:l1) l2
                then True
                else mlines ps l1 (pp:l2)
    in if check l1 l2
        then if c1 && c2
            then if length l1 < 2 || length l2 < 2
                then per p
                else False
            else if c1
                then mlines ps (p:l1) l2
                else if c2
                    then mlines ps l1 (p:l2)
                    else False
        else False


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE FlexibleContexts #-}
import Data.List (tails)
import Control.Monad.ST
import Data.Array.ST.Safe
import Data.Array (accumArray,(!))

main = do
  (n:k:as) <- map read . words <$> getContents
  let diffs = accumArray (+) 0 (0,10^6)
              [ (abs (a-b),1) | (a:t) <- tails as , b <- t ]
  print $ head $ filter (check diffs k as) [1..]

check diffs k _ m
  | sum [ diffs!d | d <- [m,2*m..10^6] ] > k*(k+1) `div` 2 = False
check diffs k as m = runST $ do
  closed <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)
  let go (-1) _ = return False
      go k (a:as) = do
        let i = a `mod` m
        c <- readArray closed i
        if c then go (k-1) as else do
          writeArray closed i True
          go k as
      go _ [] = return True
  go k as

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray)
import qualified Data.ByteString.Char8 as B
import qualified Data.IntSet as IS
import Data.List

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,k] <- map read.words <$> getLine
  xs <- sort.map readInt.B.words <$> B.getLine
  print $ solve n k xs

solve :: Int -> Int -> [Int] -> Int
solve n k xs = head $ filter check $ filter check0 [1..]
   where
     !arr = listArray (0,n-1) xs :: UArray Int Int
     !diffmax = maximum xs - minimum xs
     !lim = k*(k+1)`div`2
     !diffs = runSTUArray $ do
       d <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)
       forM_ [0..n-1] $ \i-> do
         forM_ [i+1..n-1] $ \j-> do
           unsafeModify d (unsafeAt arr j - unsafeAt arr i) (1+)
       return d
     check0 m = (<=lim) . sum $ map (unsafeAt diffs) [m,m+m..diffmax]
     check m = runST $ do
       used <- newArray (0,m) False :: ST s (STUArray s Int Bool)
       let go !cnt (x:xs)
             | cnt > k = return False
             | otherwise = do
                 let !r = x `rem` m
                 flg <- unsafeRead used r
                 if flg
                    then go (cnt+1) xs
                    else do
                      unsafeWrite used r True
                      go cnt xs
           go cnt _ = return $! cnt <= k
       go 0 xs
{-
     check m = go 0 IS.empty $ map (`rem`m) xs
      where
        go !cnt !used (x:xs)
          | cnt > k = False
          | IS.member x used = go (cnt+1) (IS.insert x used) xs
          | otherwise = go cnt (IS.insert x used) xs
        go cnt _ _ = cnt <= k
-}

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.List
import Control.Monad.ST
import Data.Array.ST.Safe
import Data.Array
import Control.Monad

main = do
  (n:k:as) <- map (fst . fromJust . B.readInt) . B.words <$> B.getContents
  let diffs = accumArray (+) 0 (0,10^6)
              [ (abs (a-b),1) | (a:t) <- tails as , b <- t ]
  print $ head $ filter (check diffs k as) [1..]

check diffs k _ m
  | sum [ diffs!d | d <- [m,2*m..10^6] ] > k*(k+1) `div` 2 = False
check diffs k as m = runST $ do
  closed <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)
  let go (-1) _ = return False
      go k (a:as) = do
        let i = a `mod` m
        c <- readArray closed i
        if c then go (k-1) as else do
          writeArray closed i True
          go k as
      go _ [] = return True
  go k as

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray)
import qualified Data.ByteString.Char8 as B
import qualified Data.IntSet as IS
import Data.List

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,k] <- map read.words <$> getLine
  xs <- sort.map readInt.B.words <$> B.getLine
  print $ solve n k xs

solve :: Int -> Int -> [Int] -> Int
solve n k xs = head $ filter check $ filter check0 [1..]
   where
     !arr = listArray (0,n-1) xs :: UArray Int Int
     !diffmax = maximum xs - minimum xs
     !lim = k*(k+1)`div`2
     !diffs = runSTUArray $ do
       d <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)
       forM_ [0..n-1] $ \i-> do
         forM_ [i+1..n-1] $ \j-> do
           unsafeModify d (unsafeAt arr j - unsafeAt arr i) (1+)
       return d
     check0 m = (<=lim) . sum $ map (unsafeAt diffs) [m,m+m..diffmax]
     check m = go 0 IS.empty $ map (`rem`m) xs
      where
        go !cnt !used (x:xs)
          | cnt > k = False
          | IS.member x used = go (cnt+1) (IS.insert x used) xs
          | otherwise = go cnt (IS.insert x used) xs
        go cnt _ _ = cnt <= k

{-# LANGUAGE FlexibleContexts #-}
import Data.List (tails)
import Data.Array.ST.Safe (STUArray,newArray,readArray,writeArray)
import Control.Monad (forM_)
import Control.Monad.ST.Safe (ST,runST)
main = interact $ show . solve . map read . words
solve (n:k:ns) = runST $ do
  a <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)
  forM_ (tails ns) $ \ns -> if null ns then return () else do
    forM_ (tail ns) $ \n -> let d = abs (head ns - n)
                            in readArray a d >>= writeArray a d . succ
  let threshold = k * (k+1) `div` 2
      validate m = go m 0 where
        go _ c | c > threshold = validate (m+1)
        go i _ | i > 1000000 = return m
        go i c = do
          c' <- readArray a i
          go (i+m) (c+c')
  validate (n-k)

{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.List
import Control.Monad.ST
import Data.Array.ST.Safe
import Data.Array
import Control.Monad

-- import Debug.Trace

main = do
  (n:k:as) <- map (fst . fromJust . B.readInt) . B.words <$> B.getContents
  let diffs = accumArray (flip (:)) [] (0,10^6)
              [ (abs (a-b),(a,b)) | (a:t) <- tails as, b <- t ]
  print $ head $ filter (check'' diffs k) [1..]

check k as m = (<= k) $ sum $ map (pred . length) $ group $ sort $ map (`mod` m) as

check' k as m = runST $ do
  t <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)
  let go (-1) _ = return False
      go k (a:as) = do
        let i = a `mod` m
        p <- readArray t i
        writeArray t i True
        go (if p then k-1 else k) as
      go _ [] = return True
  go k as

check'' diffs k m = runST $ do
  parent <- newListArray (0,10^6) [0..] :: ST s (STUArray s Int Int)
  size <- newListArray (0,10^6) (repeat 1) :: ST s (STUArray s Int Int)
  let -- go k ps | traceShow (k,ps) False = undefined
      go (-1) _ = return False
      go k ((a,b):ps) = do
        same <- liftM2 (==) (rep a) (rep b)
        if same then go k ps else do
          merge a b
          go (k-1) ps
      go _ [] = return True
      rep i = do
        p <- readArray parent i
        if p == i then return i else do
          r <- rep p
          writeArray parent i r
          return r
      merge i j = do
        -- traceM $ "Merge " ++ show (i,j)
        ri <- rep i
        rj <- rep j
        si <- readArray size ri
        sj <- readArray size rj
        if si <= sj
          then do
            writeArray parent ri rj
            writeArray size rj (si+sj)
          else do
            writeArray parent rj ri
            writeArray size ri (si+sj)
  go k $ concatMap (diffs!) [m,2*m..4999]

{- Old version

{-# LANGUAGE FlexibleContexts #-}
import Data.List (tails)
import Data.Array.ST (STUArray,newArray,readArray,writeArray)
import Control.Monad (forM_)
import Control.Monad.ST (ST,runST)
main = interact $ show . solve . map read . words
solve (n:k:ns) = runST $ do
  a <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)
  forM_ (tails ns) $ \ns -> if null ns then return () else do
    forM_ (tail ns) $ \n -> let d = abs (head ns - n)
                            in readArray a d >>= writeArray a d . succ
  let threshold = k * (k+1) `div` 2
      validate m = go m 0 where
        go _ c | c > threshold = validate (m+1)
        go i _ | i > 1000000 = return m
        go i c = do
          c' <- readArray a i
          go (i+m) (c+c')
  validate (n-k)

-}

{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.List
import Control.Monad.ST.Safe
import Data.Array.ST.Safe

main = do
  (n:k:as) <- map (fst . fromJust . B.readInt) . B.words <$> B.getContents
  print $ head $ filter (check' k as) [1..]

check k as m = (<= k) $ sum $ map (pred . length) $ group $ sort $ map (`mod` m) as

check' k as m = runST $ do
  t <- newArray (0,m-1) False :: ST s (STUArray s Int Bool)
  let go (-1) _ = return False
      go k (a:as) = do
        let i = a `mod` m
        p <- readArray t i
        writeArray t i True
        go (if p then k+1 else k) as
      go _ [] = return True
  go k as

{- Old version

{-# LANGUAGE FlexibleContexts #-}
import Data.List (tails)
import Data.Array.ST (STUArray,newArray,readArray,writeArray)
import Control.Monad (forM_)
import Control.Monad.ST (ST,runST)
main = interact $ show . solve . map read . words
solve (n:k:ns) = runST $ do
  a <- newArray (0,1000000) 0 :: ST s (STUArray s Int Int)
  forM_ (tails ns) $ \ns -> if null ns then return () else do
    forM_ (tail ns) $ \n -> let d = abs (head ns - n)
                            in readArray a d >>= writeArray a d . succ
  let threshold = k * (k+1) `div` 2
      validate m = go m 0 where
        go _ c | c > threshold = validate (m+1)
        go i _ | i > 1000000 = return m
        go i c = do
          c' <- readArray a i
          go (i+m) (c+c')
  validate (n-k)

-}


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

import           Control.Applicative
import           Control.Monad
import           Data.Array.Unboxed
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.Function
import           Data.Int
import qualified Data.IntMap.Strict    as IM
import qualified Data.IntSet           as IS
import           Data.List
import qualified Data.Map.Strict       as M
import           Data.Monoid
import           Data.Ord
import qualified Data.Set              as S
import           Data.Tuple
import           Data.Word
--import           Debug.Trace

main :: IO ()
main = do
    [n,k] <- map read.words <$> getLine
    xs <- unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine
    print $ solve k xs

solve :: Int -> [Int] -> Int
solve k0 xs0 = go 0 . group . map fromIntegral $ sort xs0
  where
    k :: Int64
    !k = fromIntegral k0
--    go res xs | traceShow xs False = undefined
    go !res (xs@(x:_):ys@(y:_):xss)
      | y <= x + k = go res (ys:xss)
      | otherwise = go (res + length xs) (ys:xss)
    go res xs = res + length (concat xs)

module Main where

import System.IO
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8

import qualified Data.Array as Array
import qualified Data.Set as Set
import qualified Data.List as List
import qualified Data.Map as Map

import Control.Monad

input :: IO BS.ByteString
input = do
  handle <- return stdin --openFile "test.txt" ReadMode
  BS.hGetContents handle

readInts :: BS.ByteString -> [Int]
readInts = map parse . C8.words
  where parse s = let Just(x,_) = C8.readInt s in x

main :: IO ()
main = do
  [n,k] <- fmap (map read . words) getLine
  bs <- input
  let weights = readInts bs
      len = length weights
      sorted = List.sort weights
      sortedA = sorted
      sortedKA = [(w + k) | w <- sorted]
      (_,acc) = foldl eat (sortedKA,0) sortedA
        where eat (arr,acc) weight = let
                middleFront = List.dropWhile (< weight) arr
                (middle,front) = List.span (< weight + k) middleFront
                in (front, acc + (length middle))
  print $ (length weights) - acc

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

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

main = interact solve

mtrace _ s = s

solve input = show (total - removed)
    where
        n:k:xs = map fastRead . words $ input :: [Int64]
        sortedXs = sortBy (flip compare) xs
        first:_ = sortedXs
        total = fromIntegral(length xs) :: Int64
        (removed, _, _) = foldl' reducer (0, first, first) sortedXs

        reducer :: (Int64, Int64, Int64) -> Int64 -> (Int64, Int64, Int64)
        reducer (answer, firstValue, minOne) currentValue
            | firstValue > currentValue && minOne <= currentValue + k = mtrace debugTrace (answer + 1, firstValue, currentValue)
            | otherwise = mtrace ("Not " ++ debugTrace) (answer, currentValue, currentValue)
            where
                debugTrace = show firstValue ++ " And " ++ show currentValue ++ " And " ++ show minOne

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

import           Control.Applicative
import           Control.Monad
import           Data.Array.Unboxed
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.Function
import           Data.Int
import qualified Data.IntMap.Strict    as IM
import qualified Data.IntSet           as IS
import           Data.List
import qualified Data.Map.Strict       as M
import           Data.Monoid
import           Data.Ord
import qualified Data.Set              as S
import           Data.Tuple
import           Data.Word

main :: IO ()
main = do
    [n,k] <- map read.words <$> getLine
    xs <- unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine
    print $ solve k xs

solve :: Int -> [Int] -> Int
solve k0 xs0 = go 0 . map fromIntegral $ sort xs0
  where
    k :: Int64
    !k = fromIntegral k0
    go !res (x:y:xs)
      | x < y, y <= x + k = go res (y:xs)
      | otherwise = go (res + 1) (y:xs)
    go res _ = res

module Main where

import System.IO
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8

import qualified Data.Array as Array
import qualified Data.Set as Set
import qualified Data.List as List
import qualified Data.Map as Map

import Control.Monad

input :: IO BS.ByteString
input = do
  handle <- return stdin --openFile "test.txt" ReadMode
  BS.hGetContents handle

readInts :: BS.ByteString -> [Int]
readInts = map parse . C8.words
  where parse s = let Just(x,_) = C8.readInt s in x

main :: IO ()
main = do
  [n,k] <- fmap (map read . words) getLine
  bs <- input
  let weights = readInts bs
      weightsPlusK = Set.fromList [(w + k) | w <- weights]
      weightsSorted = List.sort weights
      remaining = foldl eat weightsPlusK weightsSorted
        where eat set weight = let
                (ok,notOk) = Set.partition
                  (\el -> el >= weight && el < (weight + k)) set
                in set Set.\\ ok
  print $ Set.size remaining


import Data.List
import Control.Monad

getTest :: IO [Int]
getTest = do
  _ <- getLine
  r <- getLine
  let
    r' = map read $ words r
  return r'

main :: IO ()
main = do
  n <- getLine
  let n' = (read n :: Int)
  tests <- replicateM n' getTest
  mapM_ (putStrLn . unwords . map show . nub) tests

import Data.List
import qualified Data.Set as Set

main = do
    contents <- getContents
    let notnull = filter (not . null) $ lines contents
    let input = map (map (read :: String -> Int) . words) notnull
    let res = go (drop 1 input)
    sequence res

toString :: [Int] -> String
toString [] = ""
toString (x:xs) = show x ++ " " ++ toString xs

go :: [[Int]] -> [IO ()]
go [] = []
go (_:x:xs) = putStrLn res:go xs
    where res = toString (solve x)

solve :: [Int] -> [Int]
solve a =
    let recurse [] _ = []
        recurse (x:xs) s
            | Set.member x s = recurse xs s
            | otherwise = x:recurse xs (Set.insert x s)
    in recurse a Set.empty

module Main where
import Data.List

main = do
  interact $ unlines . map solve . groupl 2 . tail .lines

solve :: [String] -> String
solve (n:str:[]) = unwords . map show $ (go (toInteger $ length . words $ str) [] (map read $ words str :: [Integer]))
  where go :: Integer -> [Integer] -> [Integer] -> [Integer]
        go 0 xs ls = xs
        go n xs (l:ls) = case elem l xs of
                           True -> go (n-1) xs ls
                           False -> go (n-1) (xs ++ [l]) ls

groupl :: Int -> [a] -> [[a]]
groupl _ [] = []
groupl n l
  | n > 0 = (take n l) : (groupl n (drop n l))
  | otherwise = error "Negative or zero n"

main = interact $ unlines . map (unwords . solve []) . prepareInput . map words . tail . lines

prepareInput :: [[String]] -> [[String]]
prepareInput [] = []
prepareInput (x:[]) = []
prepareInput (x:y:xs) = concat [[x ++ y], prepareInput xs]

solve :: [String] -> [String] -> [String]
solve xs (x:[]) = xs
solve xs (x:y:ys)
  | length xs == read x = xs
  | elem y xs = solve xs (x:ys)
  | otherwise = solve (xs ++ [y]) (x:ys)

import Data.Set as Set ( empty, insert, member )
import Control.Monad ( replicateM_ )

solve :: [Integer] -> [Integer]
solve = snd . foldr go (Set.empty, []) where
  go y old@(seen, ys)
    | member y seen = old
    | otherwise     = (insert y seen, y : ys)

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n $ getLine >> getLine >>= putStrLn . unwords . map show . solve . map read . words

import Control.Monad   ( replicateM_ )

restorePerm :: [Integer] -> [Integer]-> [Integer]
restorePerm ys [] = reverse ys
restorePerm ys (x : xs)
  | elem x ys = restorePerm ys xs
  | otherwise = restorePerm (x : ys) xs

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n $ getLine >> getLine >>= solve
  where
    solve = putStrLn . unwords . map show . restorePerm [] . map read . words

module Main where

import Data.List
import Control.Monad (replicateM_)

f :: [Int] -> [Int]
f [] = []
f (x:xs) = x : f (delete x xs)

go :: IO ()
go = do
  _ <- getLine
  xs <- map read . words <$> getLine :: IO [Int]
  putStrLn . unwords . map show $ f xs

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

module Main where

import qualified Data.Set as Set

main :: IO ()
main = do
    input <- getLine
    let n = (read input :: Int)
    sequence_ $ replicate n solve

listToString :: [Int] -> String
listToString [] = ""
listToString (x : xs) = (show x) ++ " " ++ (listToString xs)

printList :: [Int] -> IO ()
printList = putStrLn . listToString

getPerm :: Set.Set Int -> Set.Set Int -> [Int] -> [Int] -> [Int]
getPerm _ _ [] ans = ans
getPerm first second (x : xs) ans = case (Set.member x first, Set.member x second) of
                                        (False, False) -> getPerm (Set.insert x first) second xs (ans ++ [x])
                                        (True,  False) -> getPerm first (Set.insert x second) xs ans
                                        (False, True)  -> getPerm (Set.insert x first) second xs ans

solve :: IO ()
solve = do
    foo <- getLine
    input <- getLine
    let perm = map read (words input) :: [Int]
    printList $ getPerm Set.empty Set.empty perm []

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

process []  y = y
process (x:xs) y | elem x y = process xs y
                 | otherwise = process xs (x:y)

onecase = do
		getLine
		a<- map read <$> words <$> getLine ::IO [Int]
		putStrLn $ intercalate " " $ map show $ reverse $ process a []

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

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

process []  y = y
process (x:xs) y | elem x y = process xs y
                 | otherwise = process xs (x:y)

onecase = do
		getLine
		a<- map read <$> words <$> getLine ::IO [Int]
		putStrLn $ intercalate " " $ map show $ process a []

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


main = interact solve
solve input = output where
  [l0,l1] = lines input
  [k,a,b] = map (read::String->Int) $ words l0
  output = answer
  len = length l1
  answer = if len < k*a || len > k*b then "No solution" else unlines $ ans0 ++ ans1
  len0 = div len k
  mod0 = mod len k
  ans0 = [take (len0+1) $ drop (i*(len0+1)) l1|i<-[0..(mod0 - 1)]]
  ans1 = [take len0 $ drop (mod0*(len0+1)+i*len0) l1|i<-[0..(k-mod0-1)]]

main = interact solve
solve input = output where
  [l0,l1] = lines input
  [k,a,b] = map (read::String->Int) $ words l0
  len = length l1
  output = if len < k*a || len > k*b then "No solution" else unlines $ ans0 ++ ans1
  len0 = div len k
  mod0 = mod len k
  ans0 = [take (len0+1) $ drop (i*(len0+1)) l1|i<-[0..(mod0 - 1)]]
  ans1 = [take len0 $ drop (mod0*(len0+1)+i*len0) l1|i<-[0..(k-mod0-1)]]


-- import Debug.Trace

import Data.List

type InType  = [Int]
type OutType = [Int]

inpLines :: Int
inpLines = 2

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

countOccs :: Eq a => [a] -> [(a, Int)]
countOccs [] = []
countOccs [x] = [(x, 1)]
countOccs (x : xs) =
    case countOccs xs of
        (a,b) : t -> if x == a
                     then (a, b + 1) : t
                     else (x, 1) : (a, b) : t
        _         -> undefined

solve :: InType -> OutType
solve a = map fst occ ++ gen occ
    where sa  = sort a
          occ = countOccs sa
          gen [] = []
          gen ((x, o) : t) = replicate (o - 1) x ++ gen t

receive :: [String] -> InType
receive [n, a] = toArr a
receive _      = undefined

main :: IO ()
main = interact (unlines . map (showArr . solve . receive) . chunksOf inpLines . tail . lines)
    where showArr = foldr (\x xs -> show x ++ " " ++ xs) ""

module Main where

import Data.List (group)
import Control.Monad (replicateM_)
main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

solve :: IO ()
solve = do
  _ <- getLine
  arr <- map read . words <$> getLine
  putStrLn . unwords . map show . reorder $ arr

reorder :: [Int] -> [Int]
reorder = f 0  where
  f x arr = case splitBy x arr of
    Nothing -> arr
    Just (a,b,c) -> b : f (x + 1) (a ++ c)

splitBy :: Int -> [Int] -> Maybe ([Int], Int, [Int])
splitBy x [] = Nothing
splitBy x (r:rs) | x == r = Just ([],r,rs)
splitBy x (r:rs) = (\(a,b,c) -> (r:a,b,c)) <$> splitBy x rs

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

import Data.Array.Unboxed

solve :: [Int] -> [Int]
solve li = let
  k = maximum li
  buckets :: UArray Int Int
  buckets = accumArray (const . (+ 1)) 0 (0, k) $ zip li $ repeat ()
  in  [ix | (ix, ct) <- assocs buckets, ct > 0] ++ do
  (ix, ct) <- assocs buckets
  guard $ ct > 0
  replicate (ct - 1) ix

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [_n] <- readInts
    a <- readInts
    putInts $ solve a

type SIO = StateT P.ByteString IO

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

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

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder

-- import Debug.Trace

import Data.List

type InType  = [Int]
type OutType = [Int]

inpLines :: Int
inpLines = 2

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

countOccs :: Eq a => [a] -> [(a, Int)]
countOccs [] = []
countOccs (x : xs) =
    case countOccs xs of
        (a,b) : t -> if x == a
                     then (a, b + 1) : t
                     else (x, 1) : (a, b) : t
        []         -> [(x, 1)]

solve :: InType -> OutType
solve a = map fst occ ++ gen occ
    where sa  = sort a
          occ = countOccs sa
          gen [] = []
          gen ((x, o) : t) = replicate (o - 1) x ++ gen t

receive :: [String] -> InType
receive [n, a] = toArr a
receive _      = undefined

main :: IO ()
main = interact (unlines . map (showArr . solve . receive) . chunksOf inpLines . tail . lines)
    where showArr = foldr (\x xs -> show x ++ " " ++ xs) ""

-- import Debug.Trace

import Data.List

type InType  = [Int]
type OutType = [Int]

inpLines :: Int
inpLines = 2

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

countOccs :: Eq a => [a] -> [(a, Int)]
countOccs [] = []
countOccs [x] = [(x, 1)]
countOccs (x : xs) = if x == (fst . head) rest
                     then addOne rest
                     else (x, 1) : rest
    where rest = countOccs xs
          addOne ((a, b) : t) = (a, b + 1) : t

solve :: InType -> OutType
solve a = map fst occ ++ gen occ
    where sa  = sort a
          occ = countOccs sa
          gen [] = []
          gen ((x, o) : t) = replicate (o - 1) x ++ gen t

receive :: [String] -> InType
receive [n, a] = toArr a

main :: IO ()
main = interact (unlines . map (showArr . solve . receive) . chunksOf inpLines . tail . lines)
    where showArr = foldr (\x xs -> show x ++ " " ++ xs) ""

import Control.Monad
import Data.List

main = do
    t <- getLine
    replicateM (read t) testcase

testcase :: IO ()
testcase = do
    n <- getLine
    a <- fmap words getLine
    putStrLn $ solve a

solve :: [String] -> String
solve a = unwords . map show $ solution
    where
        sorted = group . reverse . sort . map read $ a :: [[Int]]
        pairs = foldl (\(x,y) curr -> (head curr:x, tail curr ++ y)) ([],[]) sorted :: ([Int],[Int])
        solution = fst pairs ++ snd pairs :: [Int]

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

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

print2 [x] = ""
print2 (x:xs) = (if x == head xs then show(x) ++ " " else "") ++ print2 xs

print1 [x] = show(x) ++" "
print1 (x:xs) =  (if (x /= head xs) then show(x) ++ " " else "")  ++ print1 xs

printS = do
    n<-readLn :: IO Int
    a<-readInts
    let sorted = sort a
    putStr $ print1 sorted
    putStrLn $ print2 sorted

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

{-# LANGUAGE BangPatterns #-}

import Control.Monad
import Data.Char
import Data.List (sort)
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace
import System.IO
import Text.Read

main :: IO ()
main = do
  t <- readLn :: IO Integer
  forM_ [1 .. t] handleCase

handleCase :: Integer -> IO ()
handleCase c = do
  n <- read <$> getLine :: IO Int
  as <- fmap (map read . words) getLine :: IO [Int]
  putStrLn $ unwords $ map show $ solve (sort as) [] []

solve :: [Int] -> [Int] -> [Int] -> [Int]
solve [x] pref suff = reverse pref ++ [x] ++ suff
solve (x:y:as) pref suff
  | x==y = solve (x:as) pref (y:suff)
  | otherwise = solve (y:as) (x:pref) suff


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

check :: String -> String -> Set.Set String -> Bool
check "" suff set = False
check pref suff set =
    if suff /= "" && Set.member pref set && Set.member suff set
    then True
    else check (init pref) ((last pref) : suff) set

solve :: [String] -> Int -> Int -> Int -> Int
solve strs n i j
    | i == n `div` 2 = 0
    | j == (n + 1) `div` 2 =
        solve strs n (i+1) 0
    | otherwise =
        (min cost (4 - cost)) + solve strs n i (j+1)
        where
            ri = n - i - 1
            rj = n - j - 1
            cost = sum $ map fromEnum $ map (\x -> x == '1')
                [strs !! i !! j, strs !! j !! ri, strs !! rj !! i, strs !! ri !! rj]

testcase 0 = return ()
testcase t = do
    n <- readLn :: IO Int
    strs <- forM [1..n] (\x -> getLine)
    putStrLn $ show $ solve strs n 0 0
    testcase (t - 1)

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

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

check :: String -> String -> Set.Set String -> Bool
check "" suff set = False
check pref suff set =
    if suff /= "" && Set.member pref set && Set.member suff set
    then True
    else check (init pref) ((last pref) : suff) set

solve :: [String] -> Int -> Int -> Int -> Int
solve strs n i j =
    if i == n `div` 2
    then 0
    else if j == (n + 1) `div` 2
        then solve strs n (i+1) 0
        else (min cost (4 - cost)) + solve strs n i (j+1)
            where
                ri = n - i - 1
                rj = n - j - 1
                cost = sum $ map (\x -> if x == '1' then 1 else 0) (
                    [strs !! i !! j, strs !! j !! ri, strs !! rj !! i, strs !! ri !! rj])

testcase 0 = return ()
testcase t = do
    n <- readLn :: IO Int
    strs <- forM [1..n] (\x -> getLine)
    putStrLn $ show $ solve strs n 0 0
    testcase (t - 1)

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

import Control.Monad
import Data.List
import Data.Char
import qualified Data.ByteString.Char8 as BS

skipWhitespace :: BS.ByteString -> BS.ByteString
skipWhitespace = BS.dropWhile (`elem` " \r\n\t")

readInts :: BS.ByteString -> [Int]
readInts line = case BS.readInt line of Just (x, t) -> x : (readInts (skipWhitespace t))
                                        Nothing -> []
readInt :: BS.ByteString -> Int
readInt line = let [x] = readInts line in x

count :: Eq a => a -> [a] -> Int
count x xs = length (filter (==x) xs)

unique :: Ord a => [a] -> [a]
unique = map head . group . sort

solve n lines = sum $ map (impl . map get) $ unique $ map unique $ indexPairList
    where half = (n - 1) `div` 2
          rot (i, j) = (n - 1 - j, i)
          get (i, j) = (BS.index (lines !! i) j)
          indexPairList = [[(i, j), rot (i, j), (rot . rot) (i, j), (rot . rot . rot) (i, j)] | i <- [0 .. half], j <- [0 .. half]]
          impl xs = min (count '1' xs) (count '0' xs)

testCaseMain :: Int -> IO ()
testCaseMain _ = do n <- readInt <$> BS.getLine
                    lines <- forM [1 .. n] (\_ -> BS.getLine)
                    print (solve n lines)

main :: IO ()
main = do t <- readInt <$> BS.getLine
          forM_ [1 .. t] testCaseMain

{-# LANGUAGE LambdaCase #-}
module Main where

import Control.Monad (liftM2, replicateM_, replicateM, foldM, when)
import Data.Char (digitToInt, toLower)
import Data.Maybe (fromJust, fromMaybe, catMaybes)
import qualified Data.ByteString.Char8 as C
import Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)
import Data.List (group, sort, nub, intercalate)
import Data.Set (Set, deleteFindMin, union)
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import Data.Function (on)
-- import System.Random
import Data.Array.MArray (newArray, readArray, writeArray, newListArray)
import Data.Array.IO (IOUArray, getElems)
import Debug.Trace
import Data.Bool (bool)
import Data.Foldable (foldlM)
import Control.Arrow ((&&&), Arrow ((***)))
import Data.String (fromString)
import Data.Bits (shift)
import Data.Binary (encode, decode)

-- road map in reverse, and the number of cities, init pen state
type Domain = [[Int]]
type CoDomain = Int
type Solver  = Domain -> CoDomain

toInt :: Char -> Int
toInt '1' = 1
toInt '0' = 0

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

printAns :: CoDomain -> IO ()
printAns xs = putStrLn $ show xs

parse :: IO Domain
parse = do
  [n] <- readChar8
  xs <- replicateM n $ (fmap toInt <$> getLine)
  return xs

rotate :: Int -> (Int, Int) -> (Int, Int)
rotate n (a, b) = (n-1-b, a)

sym :: Int -> (Int, Int) -> [(Int, Int)]
sym = (take 4 .) . iterate . rotate

get :: [[Int]] -> (Int,Int) -> Int
get xs (x,y) = xs !! x !! y

cal :: [[Int]] -> [(Int, Int)] -> Int
cal xs coords = min s (4 - s)
  where n = length xs
        s = sum $ get xs <$> coords

solve :: Solver
solve xs =  sum (cal xs <$> coords) `div` 4
  where n = length xs
        indices = [0..n-1]
        coords = sym n  <$> liftM2 (,) indices indices

main :: IO ()
main = do
  [n] <- readChar8
  replicateM_ n $ printAns =<< solve <$> parse
  return ()

import           Data.List
import qualified Data.Char as DC
import qualified Data.Set as Set
import Control.Monad (replicateM)

inverseTpl :: Int -> (Int, Int, Char) -> (Int, Int, Char)

inverseTpl n (a, b, c) = (b, n - a - 1, c)

trd (_, _, z) = z
zv c = if c then 1 else 0

sumOtherF :: Int -> Set.Set (Int, Int, Char) -> (Int, Int, Char) -> Int
sumOtherF n set (a, b, c) = sumOther n set (a, b, '1')

sumOther :: Int -> Set.Set (Int, Int, Char) -> (Int, Int, Char) -> Int
sumOther n set tpl =
    let i1 = inverseTpl n
        i2 = i1 . i1
        i3 = i1 . i2
        t1 = Set.member (i1 tpl) set
        t2 = Set.member (i2 tpl) set
        t3 = Set.member (i3 tpl) set
    in (zv t1) + (zv t2) + (zv t3)

shouldChange :: Int -> Set.Set (Int, Int, Char) -> (Int, Int, Char) -> Bool
shouldChange n set (a, b, c)
    | c == '0' = sumOtherF n set (a, b, c) >= 2
    | otherwise = sumOtherF n set (a, b, c) == 0

solveCase :: IO ()
solveCase = do
    n <- fmap (read :: String -> Int) getLine
    strs <- replicateM n getLine
    let prikols = concat $ map (\ilst -> map (\tp2 -> ((fst ilst), (fst tp2), (snd tp2))) $ zip [0..n-1] (snd ilst)) $ zip [0..n-1] strs
    let setik = Set.fromList prikols
    let res = filter (shouldChange n setik) prikols
    putStrLn $ show $ length res

solve :: Int -> IO ()
solve 0 = do
    return ()
solve cases_left = do
    solveCase
    solve $ cases_left - 1

main = do
    s_testcases <- getLine
    solve $ (read s_testcases :: Int)

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

check :: String -> String -> Set.Set String -> Bool
check "" suff set = False
check pref suff set =
    if suff /= "" && Set.member pref set && Set.member suff set
    then True
    else check (init pref) ((last pref) : suff) set

solve :: [String] -> Int -> Int -> Int -> Int
solve strs n i j
    | i == n `div` 2 = 0
    | j == (n + 1) `div` 2 =
        solve strs n (i+1) 0
    | otherwise =
        (min cost (4 - cost)) + solve strs n i (j+1)
            where
                ri = n - i - 1
                rj = n - j - 1
                cost = sum $ map (\x -> if x == '1' then 1 else 0) (
                    [strs !! i !! j, strs !! j !! ri, strs !! rj !! i, strs !! ri !! rj])

testcase 0 = return ()
testcase t = do
    n <- readLn :: IO Int
    strs <- forM [1..n] (\x -> getLine)
    putStrLn $ show $ solve strs n 0 0
    testcase (t - 1)

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


import Array
import Char
main = interact (ans)
ans theInput = unlines ansList where
  s:t:n0:abw0 = lines theInput
  n = read n0 ::Int
  abw = [(c2i $ x!!0,c2i $ x!!2,read(drop 4 x)::Integer)|x<-(take n abw0)]
  c2i x = ord x - ord 'a'
  table [] = array ((0,0),(25,25)) [((a,b),if a==b then 0 else 999999999)|a<-[0..25],b<-[0..25]]
  table ((a,b,w):xs) = (table xs) // [((a,b),min w ( (table xs)!(a,b) ) )]
  wf 0 = table abw
  wf (m+1) = array((0,0),(25,25)) [((a,b),min ((wf m)!(a,b)) ( ((wf m)!(a,m))+((wf m)!(m,b)) ) ) |a<-[0..25],b<-[0..25]] where
  final = wf 26
  cost t = array((0,0),(25,25)) [((x,y),foldr1 min [( (t!(x,z)) + (t!(y,z)),z )|z<-[0..25]])|x<-[0..25],y<-[0..25]]
  total = sum [fst (cf x y)|(x,y)<-zip s t]
  answord = [chr(snd (cf x y)+ord 'a') |(x,y)<-zip s t]
  cf x y = (cost final) ! (c2i x,c2i y)
  ansList = if total>999999998 || length s /= length t then ["-1"] else [show total,answord]

import Array
import Char
main = interact (ans)
ans theInput = unlines ansList where
  s:t:n0:abw0 = lines theInput
  n = read n0 ::Int
  abw = [(c2i $ x!!0,c2i $ x!!2,read(drop 4 x)::Integer)|x<-(take n abw0)]
  c2i x = ord x - ord 'a'
  table [] = array ((0,0),(25,25)) [((a,b),if a==b then 0 else 999999999)|a<-[0..25],b<-[0..25]]
  table ((a,b,w):xs) = (table xs) // [((a,b),min w ( (table xs)!(a,b) ) )]
  wf 0 = table abw
  wf (m+1) = array((0,0),(25,25)) [((a,b),min ((wf m)!(a,b)) ( ((wf m)!(a,m))+((wf m)!(m,b)) ) ) |a<-[0..25],b<-[0..25]]
  final = wf 26
  cost t = array((0,0),(25,25)) [((x,y),foldr1 min [( (t!(x,z)) + (t!(y,z)),z )|z<-[0..25]])|x<-[0..25],y<-[0..25]]
  total = sum [fst (cf x y)|(x,y)<-zip s t]
  answord = [chr(snd (cf x y)+ord 'a') |(x,y)<-zip s t]
  cf x y = (cost final) ! (c2i x,c2i y)
  ansList = if total>999999998 || length s /= length t then ["-1"] else [show total,answord]

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

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.Set as Set
import qualified Data.ByteString.Char8 as BS
import Text.Printf
import Data.Array.IO
import Data.IORef
import Data.Int
import System.Exit
import Text.Printf
import qualified Foreign as F
import qualified Foreign.C as F

foreign import ccall unsafe "stdio.h printf"
  c_printf_I64d :: F.CString -> F.CLLong -> IO ()

foreign import ccall unsafe "stdio.h printf"
  c_printf_s :: F.CString -> F.CString -> IO ()

inf :: Int64
inf = 10 ^ 16

{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}
{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}
for_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()
for_ i n f = loop i where
  loop i | i <= n    = f i >> loop (succ i)
         | otherwise = return ()

main :: IO ()
main = do
  let exit = print (-1) >> exitSuccess
      conv = fromIntegral . fst . fromJust . BS.readInt
  table <- newArray (('a', 'a'), ('z', 'z')) inf :: IO (IOUArray (Char, Char) Int64)
  F.withCString "%I64d\n" $ \fmt_I64d -> do
    F.withCString "%s\n" $ \fmt_s -> do
      for_ 'a' 'z' $ \c -> do
        writeArray table (c, c) 0
      s1 <- BS.filter (/= '\r') <$> BS.getLine
      s2 <- BS.filter (/= '\r') <$> BS.getLine
      when (BS.length s1 /= BS.length s2) $ exit
      n <- readLn
      for_ 1 n $ \i -> do
        from : to : s : _ <- BS.words <$> BS.getLine
        let idx = (BS.head from, BS.head to)
        v <- readArray table idx
        writeArray table idx $ min (conv s) v
      for_ 'a' 'z' $ \k -> do
        for_ 'a' 'z' $ \i -> do
          for_ 'a' 'z' $ \j -> do
            v  <- readArray table (i, j)
            v1 <- readArray table (i, k)
            v2 <- readArray table (k, j)
            when (v1 + v2 < v) $ do
              writeArray table (i, j) $ v1 + v2
      -- getAssocs table >>= print . filter ((/= inf) . snd)
      r <- newIORef 0 :: IO (IORef Int64)
      buf <- F.mallocArray0 101000 :: IO F.CString
      for_ 0 (BS.length s1 - 1) $ \i -> do
        let c1 = BS.index s1 i
            c2 = BS.index s2 i
            findMin = loop 'a' ('\0', inf) where
              loop to acc@(c, v)
                | 'z' < to  = return acc
                | otherwise = do
                    v1 <- readArray table (c1, to)
                    v2 <- readArray table (c2, to)
                    -- printf "%s\n" (show (c1, c2, to))
                    loop (succ to) $ if v1 + v2 < v then (to, v1 + v2) else acc
        (c, v) <- findMin
        when (c == '\0') $ exit
        modifyIORef r $ (+ v)
        F.poke (buf `F.advancePtr` i) (toEnum . fromEnum $ c)
      F.poke (buf `F.advancePtr` (BS.length s1)) (toEnum . fromEnum $ '\0')
      readIORef r >>= c_printf_I64d fmt_I64d . fromIntegral
      c_printf_s fmt_s buf
      F.free buf

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

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

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.Set as Set
import qualified Data.ByteString.Char8 as BS
import Text.Printf
import Data.Array.IO
import Data.IORef
import Data.Int
import System.Exit
import Text.Printf
import qualified Foreign as F
import qualified Foreign.C as F

foreign import ccall unsafe "stdio.h printf"
  c_printf_I64d :: F.CString -> F.CLLong -> IO ()

foreign import ccall unsafe "stdio.h printf"
  c_printf_s :: F.CString -> F.CString -> IO ()

inf :: Int64
inf = 10 ^ 16

{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}
{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}
for_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()
for_ i n f = loop i where
  loop i | i <= n    = f i >> loop (succ i)
         | otherwise = return ()

main :: IO ()
main = do
  let exit = print (-1) >> exitSuccess
      conv = fromIntegral . fst . fromJust . BS.readInt
  table <- newArray (('a', 'a'), ('z', 'z')) inf :: IO (IOUArray (Char, Char) Int64)
  F.withCString "%I64d\n" $ \fmt_I64d -> do
    F.withCString "%s\n" $ \fmt_s -> do
      for_ 'a' 'z' $ \c -> do
        writeArray table (c, c) 0
      s1 <- BS.filter (/= '\r') <$> BS.getLine
      s2 <- BS.filter (/= '\r') <$> BS.getLine
      -- s1 <- BS.getLine
      -- s2 <- BS.getLine
      when (BS.length s1 /= BS.length s2) $ exit
      n <- readLn
      for_ 1 n $ \i -> do
        from : to : s : _ <- BS.words <$> BS.getLine
        let idx = (BS.head from, BS.head to)
        v <- readArray table idx
        writeArray table idx $ min (conv s) v
      for_ 'a' 'z' $ \k -> do
        for_ 'a' 'z' $ \i -> do
          for_ 'a' 'z' $ \j -> do
            v  <- readArray table (i, j)
            v1 <- readArray table (i, k)
            v2 <- readArray table (k, j)
            when (v1 + v2 < v) $ do
              writeArray table (i, j) $ v1 + v2
      -- getAssocs table >>= print . filter ((/= inf) . snd)
      r <- newIORef 0 :: IO (IORef Int64)
      buf <- F.mallocArray0 101000 :: IO F.CString
      for_ 0 (BS.length s1 - 1) $ \i -> do
        let c1 = BS.index s1 i
            c2 = BS.index s2 i
            findMin = loop 'a' ('\0', inf) where
              loop to acc@(c, v)
                | 'z' < to  = return acc
                | otherwise = do
                    v1 <- readArray table (c1, to)
                    v2 <- readArray table (c2, to)
                    -- printf "%s\n" (show (c1, c2, to))
                    loop (succ to) $ if v1 + v2 < v then (to, v1 + v2) else acc
        (c, v) <- findMin
        when (c == '\0') $ exit
        modifyIORef r $ (+ v)
        F.poke (buf `F.advancePtr` i) (toEnum . fromEnum $ c)
      F.poke (buf `F.advancePtr` (BS.length s1)) (toEnum . fromEnum $ '\0')
      readIORef r >>= c_printf_I64d fmt_I64d . fromIntegral
      c_printf_s fmt_s buf
      F.free buf

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

import Array
import Char
main = interact (ans)
ans theInput = unlines ansList where
  s:t:n0:abw0 = lines theInput
  n = read n0 ::Int
  abw = [(c2i $ x!!0,c2i $ x!!2,read(drop 4 x)::Int)|x<-(take n abw0)]
  c2i x = ord x - ord 'a'
  table [] = array ((0,0),(25,25)) [((a,b),if a==b then 0 else 9999)|a<-[0..25],b<-[0..25]]
  table ((a,b,w):xs) = (table xs) // [((a,b),min w ((table xs)!(a,b)))]
  wf 0 = table abw
  wf (m+1) = array((0,0),(25,25))
    [((a,b),foldr min ((wf m)!(a,b)) [ ((wf m)!(a,m)+(wf m)!(m,b)) , 9999] )|a<-[0..25],b<-[0..25]]
  final = wf 26
  cost t = array((0,0),(25,25)) [((x,y),foldr min (9999,-1) [(t!(x,z)+t!(y,z),z)|z<-[0..25]])|x<-[0..25],y<-[0..25]]
  total = sum [fst (cf x y)|(x,y)<-zip s t]
  answord = [chr(snd (cf x y)+ord 'a') |(x,y)<-zip s t]
  cf x y = (cost final) ! (c2i x,c2i y)
  ansList = if total>9998 || length s /= length t then ["-1"] else [show total,answord]

{-# 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

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

inf :: Integer
inf = 10 ^ 20

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 :: Integer))
  let mp = Map.fromListWith (Map.unionWith min) cs
      bnds = (('a', 'a'), ('z', 'z'))
  table <- newArray bnds inf :: IO (IOArray (Char, Char) Integer)
  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 == inf || new < old) $ do
            writeArray table (now, to) new
            let new' = cost + new
            old' <- readArray table (from, to)
            when (old' == inf || new' < old') $ do
              writeArray table (from, to) new'
            fill from new' to
  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, v1 + v2)
            when (null xs) $ exit
            let (c, cost) = minimumBy (comparing snd) xs
            if cost == inf
              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 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables, ForeignFunctionInterface  #-}

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.Set as Set
import qualified Data.ByteString.Char8 as BS
import Text.Printf
import Data.Array.IO
import Data.IORef
import Data.Int
import System.Exit
import Text.Printf
import qualified Foreign as F
import qualified Foreign.C as F

foreign import ccall unsafe "stdio.h puts"
  puts :: F.CString -> IO ()

inf :: Int64
inf = 10 ^ 16

{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}
{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}
for_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()
for_ i n f = loop i where
  loop i | i <= n    = f i >> loop (succ i)
         | otherwise = return ()

main :: IO ()
main = do
  let exit = print (-1) >> exitSuccess
      conv = fromIntegral . fst . fromJust . BS.readInt
  table <- newArray (('a', 'a'), ('z', 'z')) inf :: IO (IOUArray (Char, Char) Int64)
  for_ 'a' 'z' $ \c -> do
    writeArray table (c, c) 0
  s1 <- BS.filter (/= '\r') <$> BS.getLine
  s2 <- BS.filter (/= '\r') <$> BS.getLine
  when (BS.length s1 /= BS.length s2) $ exit
  n <- readLn
  for_ 1 n $ \i -> do
    from : to : s : _ <- BS.words <$> BS.getLine
    let idx = (BS.head from, BS.head to)
    v <- readArray table idx
    writeArray table idx $ min (conv s) v
  for_ 'a' 'z' $ \k -> do
    for_ 'a' 'z' $ \i -> do
      for_ 'a' 'z' $ \j -> do
        v  <- readArray table (i, j)
        v1 <- readArray table (i, k)
        v2 <- readArray table (k, j)
        when (v1 + v2 < v) $ do
          writeArray table (i, j) $ v1 + v2
  -- getAssocs table >>= print . filter ((/= inf) . snd)
  r <- newIORef 0 :: IO (IORef Int64)
  buf <- F.mallocArray0 101000 :: IO F.CString
  for_ 0 (BS.length s1 - 1) $ \i -> do
    let c1 = BS.index s1 i
        c2 = BS.index s2 i
        findMin = loop 'a' ('\0', inf) where
          loop to acc@(c, v)
            | 'z' < to  = return acc
            | otherwise = do
                v1 <- readArray table (c1, to)
                v2 <- readArray table (c2, to)
                -- printf "%s\n" (show (c1, c2, to))
                loop (succ to) $ if v1 + v2 < v then (to, v1 + v2) else acc
    (c, v) <- findMin
    when (c == '\0') $ exit
    modifyIORef r $ (+ v)
    F.poke (buf `F.advancePtr` i) (toEnum . fromEnum $ c)
  F.poke (buf `F.advancePtr` (BS.length s1)) (toEnum . fromEnum $ '\0')
  readIORef r >>= print
  puts buf
  F.free buf

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

{-# 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

inf :: Integer
inf = 10 ^ 20

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 :: Integer))
  let mp = Map.fromListWith (Map.unionWith min) cs
      bnds = (('a', 'a'), ('z', 'z'))
  table <- newArray bnds inf :: IO (IOArray (Char, Char) Integer)
  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 == inf || new < old) $ do
            writeArray table (now, to) new
            let new' = cost + new
            old' <- readArray table (from, to)
            when (old' == inf || new' < old') $ do
              writeArray table (from, to) new'
            fill from new' to
  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 == inf
              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 -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
  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 -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 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
  init <- fmap (Map.fromListWith min) . T.for [1 .. n] $ \i -> do
    from : to : v: _ <- words <$> getLine
    return ((head from, head to), (read v :: Integer))
  let mp = foldl check init ['a' .. 'z']
      check acc k = foldl f acc [(i, j) | i <- ['a' .. 'z'], j <- ['a' .. 'z']]
        where f acc' (i, j) = maybe acc' g $ do
                v1 <- Map.lookup (i, k) acc'
                v2 <- Map.lookup (k, j) acc'
                return $ v1 + v2
                where g v = maybe (Map.insert (i, j) v acc') id $ do
                        v' <- Map.lookup (i, j) acc'
                        return $ if v < v'
                                   then Map.insert (i, j) v acc'
                                   else acc'
  let best c1 c2
        | c1 == c2  = return (c1, 0)
        | otherwise = do
            xs <- fmap concat . T.for ['a' .. 'z'] $ \to -> do
              return . maybe [] (return . (,) to) $ do
                case () of
                  _ | c1 == to  -> Map.lookup (c2, to) mp
                    | c2 == to  -> Map.lookup (c1, to) mp
                    | otherwise -> do
                        v1 <- Map.lookup (c1, to) mp
                        v2 <- Map.lookup (c2, to) mp
                        return $ min v1 v2
            when (null xs) $ exit
            return $ minimumBy (comparing snd) xs
  (answer, cost) <- fmap sum . unzip <$> zipWithM best s1 s2
  -- print mp
  print cost
  putStrLn answer

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


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

readInt bs = case B.readInt bs of Just (n,_) -> n

main = getLine >> do
  cnts <- map (pred.length).group.sort.([0..9]++).map readInt.B.words <$> B.getLine
  if cnts!!0 == 0
     then print $ -1
     else putStrLn.f.solve $ cnts

f (0:_) = "0"
f ns = ns>>=show

g cnts = do
  i<-[9,8..0]
  replicate (cnts!!i) i

del i xs = let (ys,x:zs)=splitAt i xs
           in ys++(x-1):zs

solve :: [Int] -> [Int]
solve cnts = case (`mod`3) $ sum $ zipWith (*) cnts [0..9] of
             0 -> g cnts
             1 | (x:_)<-filter((>0).(cnts!!))[1,4,7] -> g $ del x cnts
               | (x:_)<-filter((>1).(cnts!!))[2,5,8] -> g $ del x $ del x cnts
               | (x:y:_)<-filter((>0).(cnts!!))[2,5,8] -> g $ del x $ del y cnts
             2 | (x:_)<-filter((>0).(cnts!!))[2,5,8] -> g $ del x cnts
               | (x:_)<-filter((>1).(cnts!!))[1,4,7] -> g $ del x $ del x cnts
               | (x:y:_)<-filter((>0).(cnts!!))[1,4,7] -> g $ del x $ del y cnts
             _ -> [-1]

import Data.Char (intToDigit)
import Data.List (sort, delete)
extract f = filter (f . (`mod` 3))
solve :: [Int] -> Maybe [Int]
solve xs
    | 0 `notElem` xs = Nothing
    | otherwise =
        case pl `mod` 3 of
            0 -> Just $ reverse ss
            1 -> factored 1
            2 -> factored 2
    where pl = sum xs
          ss = sort xs
          ms = extract (/=0) ss
          factored h = case safeFind h ms of
                (_, Just x) -> Just $ reverse $ delete x ss
                _ -> case safeFind (3 - h) ms of
                    (Just y, Just x) -> Just $ reverse $ delete y $ delete x $ ss
                    _ -> Nothing
safeFind :: Int -> [Int] -> (Maybe Int, Maybe Int)
safeFind m ps =
    case extract (==m) ps of
        [] -> (Nothing, Nothing)
        [x] -> (Nothing, Just x)
        (y:x:s) -> (Just y, Just x)

parse :: Maybe [Int] -> String
parse Nothing  = "-1"
parse (Just v) = if all (==0) v then "0" else map intToDigit v

main = putStrLn.parse.solve.map read.tail.words =<< getContents

import Data.Char (intToDigit)
import Data.List (sort, delete)
extract f = filter (f . (`mod` 3))
solve :: [Int] -> Maybe [Int]
solve xs
    | 0 `notElem` xs = Nothing
    | otherwise = if md == 0 then Just ss else factored md
    where md = sum xs `mod` 3
          ss = sort xs
          ms = extract (/=0) ss
          factored h = case extract (==h) ms of
                (x:_) -> Just (delete x ss)
                _ -> case extract (==(3 - h)) ms of
                    (y:x:_) -> Just (delete y (delete x ss))
                    _ -> Nothing
parse :: Maybe [Int] -> String
parse Nothing  = "-1"
parse (Just v) = if all (==0) v then "0" else map intToDigit (reverse v)
main = putStrLn.parse.solve.map read.tail.words =<< getContents

import Data.List

solve :: [Int] -> [Int]
solve ds
    | all (/= 0) ts = []
    | all (== 0) ts = [0]
    | otherwise = reverse ts
    where r = sum ds `mod` 3
          xs = sort ds
          ps = map (\x -> filter (\y -> y `mod` 3 == x) xs) [0, 1, 2]
          ts | r == 0 = xs
             | null $ ps !! r = xs \\ (take 2 (ps !! (3 - r)))
             | otherwise = delete (ps !! r !! 0) xs

readInput :: IO [Int]
readInput = do
    contents <- getContents
    let x:xs = words contents
        ds = map read $ take (read x) xs
    return ds

showOutput :: [Int] -> IO ()
showOutput xs = do
    putStrLn $ if null xs then "-1" else concat $ map show xs

main :: IO ()
main = do
    input <- readInput
    showOutput $ solve input

import Data.List

solve :: [Int] -> [Int]
solve ds
    | all (/= 0) ts = []
    | all (== 0) ts = [0]
    | otherwise = reverse ts
    where r = sum ds `mod` 3
          xs = sort ds
          ps = map (\x -> filter (\y -> y `mod` 3 == x) xs) [0, 1, 2]
          ts | r == 0 = xs
             | null $ ps !! r = xs \\ (take 2 (ps !! (3 - r)))
             | otherwise = delete (ps !! r !! 0) xs

readInput :: IO [Int]
readInput = do
    contents <- getContents
    let n:ns = words contents
        ds = map read $ take (read n) ns
    return ds

showOutput :: [Int] -> IO ()
showOutput ds = do
    putStrLn $ if null ds then "-1" else concat $ map show ds

main :: IO ()
main = do
    input <- readInput
    showOutput $ solve input

import Data.Char (intToDigit)
import Data.List (sort, delete)
extract f = filter (f . (`mod` 3))
solve :: [Int] -> Maybe [Int]
solve xs
    | 0 `notElem` xs = Nothing
    | all (==0) xs = Just [0]
    | otherwise =
        case pl `mod` 3 of
            0 -> Just $ reverse ss
            1 -> factored 1
            2 -> factored 2
    where pl = sum xs
          ss = sort xs
          ms = extract (/=0) ss
          factored h = case safeFind h ms of
                (_, Just x) -> Just $ reverse $ delete x ss
                _ -> case safeFind (3 - h) ms of
                    (Just y, Just x) -> Just $ reverse $ delete y $ delete x $ ss
                    _ -> Nothing
safeFind :: Int -> [Int] -> (Maybe Int, Maybe Int)
safeFind m ps =
    case extract (==m) ps of
        [] -> (Nothing, Nothing)
        [x] -> (Nothing, Just x)
        (y:x:s) -> (Just y, Just x)

parse :: Maybe [Int] -> String
parse Nothing  = "-1"
parse (Just v) = map intToDigit v

main = putStrLn.parse.solve.map read.tail.words =<< getContents

import Data.List

solve :: [Int] -> [Int]
solve xs
    | all (/= 0) ts = []
    | all (== 0) ts = [0]
    | otherwise = reverse $ sort ts
    where r = sum xs `mod` 3
          ps = map (\x -> filter (\y -> y `mod` 3 == x) xs) [0, 1, 2]
          ts | r == 0 = xs
             | null $ ps !! r = xs \\ (take 2 (ps !! (3 - r)))
             | otherwise = delete (ps !! r !! 0) xs

readInput :: IO [Int]
readInput = do
    contents <- getContents
    let x:xs = words contents
        ds = map read $ take (read x) xs
    return ds

showOutput :: [Int] -> IO ()
showOutput xs = do
    putStrLn $ if null xs then "-1" else concat $ map show xs

main :: IO ()
main = do
    input <- readInput
    showOutput $ solve input