-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

import qualified Data.Map as M
import Data.Char

main = print . solve . words =<< getContents

solve [ks, ns] = ans where
    k = read ks :: Int
    (cn, mp) = foldl f (0, M.empty) $ map digitToInt ns
    f (c, m) d = (c + d, M.insertWith (+) d 1 m)
    ans = if cn >= k then 0
          else snd $ foldl g (cn, 0) [0..8]
    g t@(c, x) i | c >= k    = t
                 | otherwise =
                    case M.lookup i mp of
                    Nothing -> t
                    Just p  ->
                        let j = 9 - i
                            w = k - c
                            e = max 1 $ div (w + j - 1) j
                            v = min e p
                        in (c + v * j, x + v)

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

main = do
  k <- fmap readInt B.getLine
  n <- getLine
  print $ solve k n

solve k n
  | s >= k = 0
  | otherwise = (1+) $ length $ takeWhile (< k) $ tail $ scanl (\s d -> s - d + 9) s xs
  where
    xs = sort $ map digitToInt n
    s = sum xs

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

import Control.Applicative
import Data.Char
import Data.Int
import Data.List

run ::  Int32 -> [Int] -> Int
run _ [] = 0
run sum (c:cs) | sum <= 0   = 0
               | otherwise  = 1 + (run (sum-m) cs)
               where m = 9 - (fromIntegral c)

solve :: Int32 -> [Int] -> Int
solve k s = run (k - (fromIntegral $ sum s)) s

main = do
  k <- read <$> getLine
  s <- sort . (map digitToInt) <$> getLine
  print $ solve k s

import Data.List
import Data.Char
main =
  do
    sk <- getLine
    let k = read sk :: Int
    sn <- getLine
    let sv = (map digitToInt $ sort sn) :: [Int]
        allsum = sum sv

    if k <= allsum
       then print 0
       else
         print.snd $ foldl (\(acc, acci) x -> if acc > 0
                                     then (acc - 9 + x, acci + 1)
                                     else (acc, acci)) (k - allsum, 0) sv

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

readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
readInteger :: B.ByteString -> Integer
readInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$"readInteger error : bs = "++show bs;}

main :: IO ()
main = do
    k <- readLn
    ns <- map digitToInt.B.unpack.B.filter(\c->'0'<=c&&c<='9') <$> B.getLine
    print $ solve k ns

solve :: Int -> [Int] -> Int
solve k ns = go 0 (k - s) $ sort ns
  where
    !s = sum ns
    go !res !rest (x:xs)
      | rest <= 0 = res
      | otherwise = go (res + 1) (rest - (9 - x)) xs
    go res _ _ = res

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

readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
readInteger :: B.ByteString -> Integer
readInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$"readInteger error : bs = "++show bs;}

main :: IO ()
main = do
    k <- readLn
    ns <- map digitToInt.B.unpack.B.filter(\c->'0'<=c&&c<='9') <$> B.getLine
    putStrLn . concatMap show $ solve k ns

solve :: Int -> [Int] -> [Int]
solve k ns = go [] (k - s) $ reverse ns ++ repeat 0
  where
    !s = sum ns
    go !res !rest (x:xs)
      | rest <= 0 = [0]
      | 9 - x >= rest = rest:res
      | otherwise = go ((9-x):res) (rest-(9-x)) xs

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

main = do
  k <- fmap readInt B.getLine
  n <- getLine
  print $ solve k n

solve k n
  | need <= 0 = 0
  | otherwise = ceiling $ (fromIntegral need + 1) / 9
  where
    xs = map digitToInt n
    need = k - sum xs

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

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

import qualified Data.Map as M
import Data.Char

main = print . solve . words =<< getContents

solve [ks, ns] = ans where
    k = read ks :: Int
    (cn, mp) = foldl f (0, M.empty) $ map digitToInt ns
    f (c, m) d = (c + d, M.insertWith (+) d 1 m)
    ans = if cn >= k then 0
          else snd $ foldl g (cn, 0) [0..8]
    g t@(c, x) i | c >= k    = t
                 | otherwise =
                    case M.lookup i mp of
                    Nothing -> t
                    Just p  ->
                        let j = 9 - i
                            w = k - c
                            e = max 1 $ div w j
                            v = min e p
                        in (c + v * j, x + v)

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

import qualified Data.Map as M
import Data.Char

main = print . solve . words =<< getContents

solve [ks, ns] = ans where
    k = read ks :: Int
    (cn, mp) = foldl f (0, M.empty) $ map digitToInt ns
    f (c, m) d = (c + d, M.insertWith (+) d 1 m)
    ans = if cn >= k then 0
          else snd $ foldl g (cn, 0) [0..8]
    g t@(c, x) i | c >= k    = t
                 | otherwise =
                    case M.lookup i mp of
                    Nothing -> t
                    Just p  ->
                        let j = 9 - i
                            w = k - c
                            e = max 1 $ quot w j
                            v = min e p
                        in (c + v * j, x + v)


import List
import Char

solve :: String -> String -> String
solve _ [] = "YES"
solve [] _ = "NO"
solve (x:xs) (y:ys)
  | x == y  =  solve xs ys
  | x <  y  =  solve xs (y:ys)
  | x >  y  =  "NO"

main = do
  s1 <- getLine
  s2 <- getLine
  putStrLn $ solve (sort $ filter isAlpha s1) (sort $ filter isAlpha s2)

import Data.List ((\\))

main = do
	a <- getLine
	b <- getLine
	putStrLn $ if filter (/= ' ') b \\ a == [] then "YES" else "NO"

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

readall = State (,"")

runRead x s = fst $ runState x s

main = reader >>= writer . solver
reader = getContents
writer = putStr
solver = runRead $ do
	(s1:s2:_)<-liftM lines readall
	let count c s = length . filter (==c) $ s
	let chars = ['a'..'z'] ++ ['A'..'Z']
	return (if and [count c s1 >= count c s2 | c<-chars] then "YES" else "NO")

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

count s = \x -> (C.length . C.filter ((==) x)) s

main = do
	input <- fmap C.lines $ C.hGetContents stdin
	let [s1,s2] = take 2 $ input
	let ans = length $ filter (==False) $ [ count s1 c >= count s2 c | c <- ['a'..'z'] ++ ['A'..'Z'] ]
	putStrLn (if ans == 0 then "YES" else "NO")

import Data.List
f xs = [x | x <- xs, x/=' ']
solve s s2 | null s2 = "YES"| null s = "NO" | head s2 `elem` s  = solve x z | otherwise = "NO"
    where
        x = delete y s
        y = head s2
        z = tail s2
main = do
    s <- fmap f getLine
    s2 <- fmap f getLine
    putStrLn $ solve s s2

main = do l1 <- getLine
          l2 <- getLine
          if solve l1 l2 then putStrLn "YES" else putStrLn "NO"

solve :: String -> String -> Bool
solve _ [] = True
solve [] _ = False
solve cs1 (c2:cs2) = if c2 == ' '
                     then solve cs1 cs2
                     else case (find "" cs1 c2) of
                            Just cs -> solve cs cs2
                            Nothing -> False
    where
      nl = length cs1
      find :: String -> String -> Char -> Maybe String
      find _ [] c = Nothing
      find cs (c':cs') c = if c == c'
                           then Just (cs ++ cs')
                           else find (c':cs) cs' c

import Data.List

main = do
  t <- getLine
  h <- getLine

  putStrLn $ m (f t) (f h)

m _ [] = "YES"
m [] _ = "NO"
m (a:as) (b:bs)
 | a == b = m as bs
 | otherwise = m as (b:bs)

f = sort . filter (/=' ')

import List
main=interact(s.lines)
s [p,f] = if null(c f\\c p)then"YES"else"NO"where c=filter(>' ')

import Data.List ((\\))

main = do
        xs <- getLine
        ys <- getLine
        putStrLn $ if null $ filter (/= ' ') ys \\ xs then "YES" else "NO"

import List
main = interact solve
solve input = output where
  [s1,s2] = lines input
  output = answer s1 s2
answer _ [] = "YES"
answer xs (y:ys)
  | elem y xs = answer (delete y xs) ys
  | y == ' '  = answer xs ys
  | otherwise = "NO"

import Data.List

main = do
  text <- getLine
  heading <- getLine

  let fh = f heading
  let tmp = f text `intersect` fh
  print $ if sort tmp == sort fh
    then "YES"
    else "NO"

f = filter (/=' ')

import Data.List

main = do
  text <- getLine
  heading <- getLine

  let fh = f heading
  let tmp = f text `intersect` fh
--  print $ sort fh
--  print $ sort tmp
  print $ m (sort tmp) (sort fh)

m _ [] = "YES"
m [] _ = "NO"
m (a:as) (b:bs)
 | a == b = m as bs
 | otherwise = m as (b:bs)

f = filter (/=' ')

import Data.List

main = do
  text <- getLine
  heading <- getLine

  let fh = f heading
  let tmp = f text `intersect` fh
  print $ m (sort tmp) (sort fh)

m [] _ = "NO"
m _ [] = "YES"
m (a:as) (b:bs)
 | a == b = m as bs
 | otherwise = m as (b:bs)

f = filter (/=' ')

import Data.List

main = do
  text <- getLine
  heading <- getLine

  let fh = f heading
  print $ sort fh
  print $ sort text
  print $ m (sort $ f text) (sort fh)

m _ [] = "YES"
m [] _ = "NO"
m (a:as) (b:bs)
 | a == b = m as bs
 | otherwise = m as (b:bs)

f = filter (/=' ')

import Data.List

main = do
  text <- getLine
  heading <- getLine

  let fh = f heading
  print $ m (sort $ f text) (sort fh)

m _ [] = "YES"
m [] _ = "NO"
m (a:as) (b:bs)
 | a == b = m as bs
 | otherwise = m as (b:bs)

f = filter (/=' ')


--{-# LANGUAGE Safe #-}
--{-# OPTIONS_GHC -O2 #-}

import {-safe-} Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe
import qualified Data.Array as A

main :: IO ()
main = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where
  tcio :: [T.Text] -> [String]
  tcio [] = []
  tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (take 2 rest) ++ tcio (drop 2 rest)
  linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;
  linetois = (map linetoi).(T.words); linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: [[Int]] -> Integer
solve [ks,cs] = sum $ map toInteger $ zipWith min sks (cs ++ (repeat (10^9+1))) where
  sks = map (vcs A.!) $ sortOn negate ks
  vcs = A.listArray (1,length cs) (cs)

{-# LANGUAGE BangPatterns #-}

import Control.Arrow
import Control.Monad
import Data.Char
import Data.List (sort)
import Data.Map.Strict (fromList, (!))
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace
import System.IO
import Text.Read
import Data.Maybe (fromJust)

getNums :: IO [Int]
getNums = do
  line <- B.getLine
  return $ map ((fst . fromJust) . B.readInt) . B.split ' ' $ line

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

handleCase :: Integer -> IO ()
handleCase c = do
  [n, m] <- fmap (map read . words) getLine :: IO [Int]
  k <- getNums :: IO [Int]
  c <- getNums :: IO [Int]
  print $ solve n m k c
  return ()

type State = (Int, Int)

inf = 10^9 + 30 :: Int

solve :: Int -> Int -> [Int] -> [Int] -> Integer
solve !n !m !k !c =
  let !sortedK = sort k
      !mapC = fromList $ zip [1 ..] c

      countExcess :: State -> Int -> State
      countExcess (idx, mx) i = (idx + 1, max mx (idx - i))

      (_, !mx) = foldl countExcess (1, 0) sortedK

      !costs = map (mapC !) sortedK
      !paddedC = if n <= m then take n c else  c ++ replicate (n - m) inf

      !startCost = sum $ map toInteger $ take n paddedC :: Integer
      !tradeOffs = zip costs (reverse paddedC)

      !a = takeWhile (uncurry (<)) tradeOffs
      !a' = if length a < mx then take mx tradeOffs else a

      !result = startCost + sum (map (\(a, b) -> toInteger a - toInteger b) a')

   in result

{-# LANGUAGE DeriveFunctor       #-} -- hasker's code
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

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

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

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

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

solve :: Int -> [Int] -> Int -> [Int64] -> Int64
solve n ks m cs = solve' 1 ksSorted
    where
        ksSorted = reverse $ sort ks
        csArray = A.listArray (1, m) cs
        solve' _ [] = 0
        solve' currK ks@(k : restKs)
            | currK <= k = csArray A.! currK + solve' (currK + 1) restKs
            | otherwise  = csArray A.! k + solve' currK restKs

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

{-# LANGUAGE DeriveFunctor       #-} -- Hasker's code
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

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

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

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

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

solve :: Int -> [Int] -> Int -> [Int64] -> Int64
solve n ks m cs = sum $ map fromIntegral $ zipWith min sks (cs ++ (repeat (10^9+1))) where
  sks = map (vcs A.!) $ sortOn negate ks
  vcs = A.listArray (1,m) cs
{-
solve :: Int -> [Int] -> Int -> [Int64] -> Int64
solve n ks m cs = solve' 1 ksSorted
    where
        ksSorted = reverse $ sort ks
        csArray = A.listArray (1, m) cs
        solve' _ [] = 0
        solve' currK ks@(k : restKs)
            | currK <= k = csArray A.! currK + solve' (currK + 1) restKs
            | otherwise  = csArray A.! k + solve' currK restKs
-}

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

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}

import safe Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe
import safe qualified Data.Array as A

main :: IO ()
main = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where
  tcio :: [T.Text] -> [String]
  tcio [] = []
  tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (nm:(take 2 rest)) ++ tcio (drop 2 rest)
  linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;
  linetois = (map linetoi).(T.words); linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: [[Int]] -> Integer
solve [[n,m],ks,cs] = sum $ map toInteger $ zipWith min sks (cs ++ (repeat (10^9+1))) where
  sks = map (vcs A.!) $ sortOn negate ks
  vcs = A.listArray (1,m) cs

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}

import safe Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe
import qualified Data.Map as M

main :: IO ()
main = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where
  tcio :: [T.Text] -> [String]
  tcio [] = []
  tcio (nm : rest) = ((:[]).itoline . solve . linestoiss) (take 2 rest) ++ tcio (drop 2 rest)
  linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;
  linetois = (map linetoi).(T.words); linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: [[Integer]] -> Integer
solve [ks,cs] = sum $ zipWith min sks (cs ++ (repeat (10^9+1))) where
  sks = reverse $ map (mic M.!) $ sort ks
  mic = M.fromList (zip [1..] cs)

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

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

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

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

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

solve :: Int -> [Int] -> Int -> [Int64] -> Int64
solve n ks m cs = solve' 1 ksSorted
    where
        ksSorted = reverse $ sort ks
        csArray = A.listArray (1, m) cs
        solve' _ [] = 0
        solve' currK ks@(k : restKs)
            | currK <= k = csArray A.! currK + solve' (currK + 1) restKs
            | otherwise  = csArray A.! k + solve' currK restKs

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

import Control.Arrow
import Control.Monad
import Data.Char
import Data.List (sort)
import Data.Map (fromList, (!))
-- 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, m] <- fmap (map read . words) getLine :: IO [Int]
  k <- fmap (map read . words) getLine :: IO [Int]
  c <- fmap (map read . words) getLine :: IO [Int]
  print $ solve n m k c
  return ()

type State = (Int, Int)

inf = 10^9 + 30 :: Int

solve :: Int -> Int -> [Int] -> [Int] -> Integer
solve n m k c =
  let sortedK = sort k
      mapC = fromList $ zip [1 ..] c

      countExcess :: State -> Int -> State
      countExcess (idx, mx) i = (idx + 1, max mx (i - idx))

      (_, mx) = foldl countExcess (1, 0) sortedK

      costs = map (mapC !) sortedK
      paddedC = if n <= m then c else  c ++ replicate (n - m) inf

      startCost = sum $ map toInteger $ take n paddedC
      tradeOffs = zip costs (reverse paddedC)

      a = takeWhile (uncurry (<)) $ tradeOffs
      a' = if length a < mx then take mx tradeOffs else a

      result = startCost + sum (map (\(a, b) -> toInteger a - toInteger b) a')

   in result


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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out > tmp.txt  &&  diff -sdu -- output.txt tmp.txt  &&  cat -- tmp.txt)

import Prelude
import Control.Monad
import Data.List

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t getLine

    (putStr . unlines . map (show . solve)) tcs

solve s = cntOnes `div` 2 + (length s' - cntOnes)
  where
    s' = reverse . sort . map length . group . sort $ s
    cntOnes = length . filter (==1) $ s'

module Main where
import Data.List (group, sort)
main = interact solve

solve :: String -> String
solve inp =
    let
        t = read . head . lines $ inp :: Int
        arr = take t . tail . lines $ inp
        more x = (length . filter (\y -> length y >= 2) . group . sort $ x) * 2
        one x = (length . filter (\y -> length y == 1) . group . sort $ x)
        logic x = if one x < more x then one x * 2 else more x * 2
    in
        unlines . map (show . (\x -> (one x + more x) `div` 2)) $ arr

import Data.List (intersperse, intercalate, sort, group)

parseOut :: [Int] -> String
parseOut = intercalate "\n" . map show

parseIn :: String -> [String]
parseIn = tail . words

solve :: String -> Int
solve str = gtOne + div one 2 where
    frequencies = map length $ group $ sort str
    gtOne = length $ filter (>1) frequencies
    one = length $ filter (==1) frequencies

main :: IO ()
main = interact $ parseOut . map solve . parseIn

import Control.Arrow ((>>>))
import Data.Set (fromList, toList)

unique :: Ord a => [a] -> [a]
unique = toList . fromList

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

solve :: String -> Int
solve s = (map ((`count` s) >>> min 2) >>> sum >>> (`div` 2)) $ unique s

main :: IO ()
main = interact $ lines >>> tail >>> map (solve >>> show) >>> unlines

import Control.Arrow ((>>>))
import Data.Bifunctor (bimap)
import Data.List (group, groupBy, sort, sortBy)
import Data.Ord (comparing)

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> map (solve >>> count 1 >>> show)
      >>> unlines

type Col = (Int, Maybe Int)

solve :: [Char] -> [Int]
solve as =
  let k = 2
   in map (maybe 0 ((1 +) . (`mod` k)) . snd)
        . sortOn fst
        . uncurry (++)
        . bimap (`zip` (Just <$> [1 ..])) (`zip` repeat Nothing)
        . (\(cs, ws) -> let (ws', cs') = splitAt (length cs `mod` k) cs in (cs', ws' ++ ws))
        . bimap' concat
        . unzip
        . map (splitAt k . map snd)
        . groupOn fst
        . sortOn fst
        $ as `zip` [0 ..]

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

groupOn :: (Eq b) => (a -> b) -> [a] -> [[a]]
groupOn p = groupBy (\x y -> p x == p y)

sortOn :: (Ord b) => (a -> b) -> [a] -> [a]
sortOn = sortBy . comparing

bimap' f = bimap f f

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

import Control.Monad (replicateM_)
import qualified Data.Map as M

counts :: Ord k => [k] -> M.Map k Int
counts = foldr insrt M.empty where
  insrt k mp = M.insertWith (+) k 1 mp

numRed :: String -> Int
numRed s = evenCnt + oddCnt + oneCnt `div` 2
  where
    cnt = counts s
    evenCnt = M.size $ M.filter even cnt
    oddCnt = M.size $ M.filter (\x -> odd x && x > 1) cnt
    oneCnt = M.size $ M.filter (==1) cnt

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    s <- getLine
    print $ numRed s

import qualified Data.Map as M
import Data.Map (Map)
import Control.Monad
import Data.Functor ((<&>))
import Data.STRef
import Control.Monad.ST

-- | Take a sequence of elements and convert into frequency mapping
collect :: Ord a => [a] -> Map a Int
collect = foldl ins_ M.empty
  where
    ins_ m n = M.alter (Just . maybe 1 (+1)) n m

-- | calculate coloring
coloring :: Ord a => [a] -> Int
coloring xs = gt2 + lt2 `div` 2
  where
    m = collect xs
    gt2 = length $ filter (>= 2) $ M.elems m
    lt2 = length m - gt2

main :: IO ()
main = do
  testCases <- read <$> getLine
  forM_ [1..testCases] $ \_ -> do
    test <- getLine
    print $ coloring test

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char

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

import qualified Data.ByteString as Bs
import qualified System.IO as Io
--import Data.IntSet

solve :: IO ()
solve = do
  a <- getLine
  let k = 2
      b = group $ sort a
      total = foldl (\acc xs -> acc + min (length xs) k) 0 b
    in print $ div total 2

main = do
  t <- readLn :: IO Int
  replicateM_ t $ solve

----------------------------------------------------------------------------------------
readrows :: (Integral a, Integral b) => b -> IO [[a]]
readrows 0 = return []
readrows n = do
  row <- readInts
  l <- readrows $ n-1
  return (row : l)

parseInt :: (Integral a) => Bs.ByteString -> a
parseInt xs = snd $ Bs.foldr (\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs

readInts :: (Integral a) => IO [a]
readInts =  map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine
  where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs

import Control.Monad
import Data.List

printResult = do
    s <- getLine
    let a = concatMap (take 2)  (group $ sort s)
    print $ div (length a) 2

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

module Main where
import Data.List (group)
main = interact solve

solve :: String -> String
solve inp =
    let
        t = read . head . lines $ inp :: Int
        arr = take t . tail . lines $ inp
        logic x = ((length . filter(\y -> length y == 1) . group $ x) `div` 2) + (length . filter (\y -> length y == 2) . group $ x)  + (length . filter(\y -> length y > 2) . group $ x)
    in
        unlines . map (show . logic) $ arr

module Main where
import Data.List (group)
main = interact solve

solve :: String -> String
solve inp =
    let
        t = read . head . lines $ inp :: Int
        arr = take t . tail . lines $ inp
        logic x = (length . filter(\y -> length y == 1) . group $ x) `div` 2 + (length . filter (\y -> length y > 1) . group $ x) `div` 2  + (length . filter(\y -> length y > 2) . group $ x)
    in
        unlines . map (show . logic) $ arr


import Data.List
main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words) getLine :: IO [Int]
    mapM_ putStr (map (\x -> (show x ++ " ")) (solve n (sort a)))

solve :: Int -> [Int] -> [Int]
solve n l =
    let (x,y) = splitAt (n `div` 2) l
    in merge x (reverse y)
     where merge [] b = b
           merge a [] = a
           merge (a:as) (b:bs) = a:b:merge as bs

import Data.List

main :: IO()
main = putStrLn . unwords . map show . solve . map read . words =<< getContents

solve :: [Int] -> [Int]
solve (n:a) = let b = sort a
                  h = div (n + 1) 2
                  (l, r) = splitAt h b
              in solve' l r
              where solve' :: [Int] -> [Int] -> [Int]
                    solve' [] [] = []
                    solve' l [] = l
                    solve' (l:ls) (r:rs) = l : r : solve' ls rs

import Data.List (sort)

main = do
  getLine
  as <- fmap (map read . words) getLine :: IO [Int]

  let
    rev (a:b:xs) = (b:a:rev xs)
    rev [a] = [a]
    rev [] = []

  putStrLn $ unwords $ map show $ rev $ reverse $ sort as

import Data.List
main=interact$unwords.map show.f1.sort.map (read::String->Int).tail.words
f1 []=[]
f1 (a:b)=a:f2 b
f2 []=[]
f2 a=last a:f1 (init a)

import Data.List

main = interact $ unwords . map show . sol . map read . tail . words

sol :: [Int] -> [Int]
sol xs
    | odd $ length xs = weave (tail sxs) ++ [head sxs]
    | otherwise = weave sxs
    where
    sxs = sort xs
    weave xs = concat $ zipWith (\a b -> [a, b]) l r
        where
        (l, r) = splitAt (length sxs `div` 2) $ sort xs


{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.Int
import Data.List
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

newtype State s a = State { runState :: s -> (a,s) }

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

instance Monad (State s) where
    return x = State $ \s -> (x,s)
    x >>= f  = State $ \s ->
        let (a,s') = runState x s in runState (f a) s'

instance Applicative (State s) where
    pure = return
    (<*>) = ap

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = maximizeBy cmpFst
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]
maximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,k] <- map readInt. B.words <$> B.getLine
    l     <- map readInt . B.words <$> B.getLine
    let (a,b) = solve n k l
    putStrLn $ show a ++" "++show b

solve n k l = snd $ foldl1 g (reverse cs)
    where
    l'  = map fromIntegral l
    costs = totalAbsurdity k l'
    as  = zip costs [1..]
    bs  = drop k $ scanr1 g as
    cs  = zipWith (\(a,ai) (b,bi) -> (a+b,(ai,bi))) as bs
    f (a,b) (c,d) = case compare a c of
        EQ -> compare d b
        a  -> a
    g a b = case f a b of
        LT -> b
        GT -> a
        EQ -> a

totalAbsurdity :: Int -> [Int64] -> [Int64]
totalAbsurdity k l = go (sum $ take k l) l (drop k l)
    where go a h []          = [a]
          go a (h:hs) (t:ts) =
            let a'   = a-h+t in
                a' `seq` a:go a' hs ts

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

newtype State s a = State { runState :: s -> (a,s) }

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

instance Monad (State s) where
    return x = State $ \s -> (x,s)
    x >>= f  = State $ \s ->
        let (a,s') = runState x s in runState (f a) s'

instance Applicative (State s) where
    pure = return
    (<*>) = ap

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = maximizeBy cmpFst
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]
maximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,k] <- map readInt. B.words <$> B.getLine
    l     <- map readInt . B.words <$> B.getLine
    let (a,b) = solve n k l
    putStrLn $ show a ++" "++show b

solve n k l = snd $ foldl1 g (reverse cs)
    where
    l'  = map toInteger l
    costs = totalAbsurdity k l'
    as  = zip costs [1..]
    bs  = drop k $ scanr1 g as
    cs  = zipWith (\(a,ai) (b,bi) -> (a+b,(ai,bi))) as bs
    f (a,b) (c,d) = case compare a c of
        EQ -> compare d b
        a  -> a
    g a b = case f a b of
        LT -> b
        GT -> a
        EQ -> a

totalAbsurdity k l = go (sum $ take k l) l (drop k l)
    where go a h []          = [a]
          go a (h:hs) (t:ts) =
            let a'   = a-h+t in
                a' `seq` a:go a' hs ts

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

newtype State s a = State { runState :: s -> (a,s) }

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

instance Monad (State s) where
    return x = State $ \s -> (x,s)
    x >>= f  = State $ \s ->
        let (a,s') = runState x s in runState (f a) s'

instance Applicative (State s) where
    pure = return
    (<*>) = ap

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

scanl' f q ls = q : case ls of
    [] -> []
    x:xs -> let q' = f q x in scanl' f q' xs
scanl1' f (x:xs) = scanl f x xs
scanl1' _ [] = []

scanr' _ q [] = [q]
scanr' f q (x:xs) =
    let qs@(q':_) = scanr f q xs in q' `seq` (f x q:qs)

scanr1' _ [] = []
scanr1' _ [x] = [x]
scanr1' f (x:xs) = q `seq` (f x q : qs)
    where qs@(q:_) = scanr1 f xs

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = maximizeBy cmpFst
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]
maximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,k] <- map readInt. B.words <$> B.getLine
    l     <- map readInt . B.words <$> B.getLine
    let (a,b) = solve n k l
    putStrLn $ show a ++" "++show b

solve n k l = snd $ foldl1' g (reverse cs)
    where
    l'  = map toInteger l
    costs = totalAbsurdity k l'
    as  = zip costs [1..]
    bs  = drop k $ scanr1 g as
    cs  = zipWith (\(a,ai) (b,bi) -> (a+b,(ai,bi))) as bs
    f (a,b) (c,d) = case compare a c of
        EQ -> compare d b
        a  -> a
    g a b = case f a b of
        LT -> b
        GT -> a
        EQ -> a

totalAbsurdity k l = go (sum $ take k l) l (drop k l)
    where go a h []          = [a]
          go a (h:hs) (t:ts) =
            let a'   = a-h+t in
                a' `seq` a:go a' hs ts

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.Int
import Data.List
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

newtype State s a = State { runState :: s -> (a,s) }

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

instance Monad (State s) where
    return x = State $ \s -> (x,s)
    x >>= f  = State $ \s ->
        let (a,s') = runState x s in runState (f a) s'

instance Applicative (State s) where
    pure = return
    (<*>) = ap

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = maximizeBy cmpFst
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]
maximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,k] <- map readInt. B.words <$> B.getLine
    l     <- map (fromIntegral.readInt) . B.words <$> B.getLine
    let (a,b) = solve n k l
    putStrLn $ show a ++" "++show b

solve n k l = snd $ foldl1 g cs
    where
    costs = totalAbsurdity k l
    as  = zip costs [1..]
    bs  = scanl1 g (reverse $ drop k as)
    cs  = zipWith (\(a,ai) (b,bi) -> (a+b,(ai,bi))) (drop k (reverse as)) bs
    f (a,b) (c,d) = case compare a c of
        EQ -> compare d b
        a  -> a
    g a b = case f a b of
        LT -> b
        GT -> a
        EQ -> a

totalAbsurdity :: Int -> [Int64] -> [Int64]
totalAbsurdity k l = go (sum $ take k l) l (drop k l)
    where go a h []          = [a]
          go a (h:hs) (t:ts) =
            let a'   = a-h+t in
                a' `seq` a:go a' hs ts

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

newtype State s a = State { runState :: s -> (a,s) }

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

instance Monad (State s) where
    return x = State $ \s -> (x,s)
    x >>= f  = State $ \s ->
        let (a,s') = runState x s in runState (f a) s'

instance Applicative (State s) where
    pure = return
    (<*>) = ap

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = maximizeBy cmpFst
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]
maximizeBy c f l = snd $ maximumBy c [(f x,x)| x<- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,k] <- map readInt. B.words <$> B.getLine
    l     <- map readInt . B.words <$> B.getLine
    let (a,b) = solve n k l
    putStrLn $ show a ++" "++show b

solve n k l = snd $ foldl1' g cs
    where
    l' = map toInteger l
    costs = totalAbsurdity k l'
    as = zip costs [1..]
    bs = drop k $ reverse $ scanl1 g $ reverse as
    cs  = zipWith (\(a,ai) (b,bi) -> (a+b,(ai,bi))) as bs
    f (a,b) (c,d) = case compare a c of
        EQ -> compare d b
        a  -> a
    g a b = case f a b of
        LT -> b
        GT -> a
        EQ -> a

totalAbsurdity k l = go (sum (take k l)) l (drop k l) []
    where go a h [] acc = reverse (a:acc)
          go a (h:hs) (t:ts) acc =
            let acc' = a:acc
                a'   = a-h+t
            in
                acc' `seq` a' `seq` go a' hs ts acc'

{-# LANGUAGE BangPatterns #-}

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

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

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

solve :: Int -> Int -> [Int64] -> [Int]
solve n k xs = snd.foldl1' max' $ zipWith (&) ls rs
   where
     xis = zip (sumK k xs) [1..]
     ls = take (n-2*k+1) xis
     rs = scanr1 max' $ drop k xis
     (x,i) & (y,j) = (x+y,[i,j])

max' :: (Ord a, Ord b) => (a,b) -> (a,b) -> (a,b)
max' xy@(x,_) zw@(z,_)
  | x == z = min xy zw
  | otherwise = max xy zw

sumK :: Int -> [Int64] -> [Int64]
sumK k xs = go (sum ys) ys [] zs
   where
     (ys,zs) = splitAt k xs
     go !acc _ _ [] = [acc]
     go !acc (f:fs) rs (x:xs) = acc : go (acc-f+x) fs (x:rs) xs
     go !acc [] rs xs = go acc (reverse rs) [] xs

import Control.Applicative
import Control.Arrow
import Data.Int
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as BS

readInt64 :: BS.ByteString -> Int64
readInt64 = fromIntegral . readInt

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

maxElem :: [Int64] -> Int
maxElem arr = fromMaybe (-1) $ elemIndex (foldl1 max arr) arr

solve :: [Int64] -> Int -> (Int, Int)
solve arr k =
	let pSum = scanl (+) 0 arr
	    pSeg = zipWith (-) (drop k pSum) pSum
	    afst = maxElem $ zipWith (+) pSeg (drop k $ scanr1 max pSeg)
	    asnd = maxElem $ drop (afst + k) pSeg
	in (1 + afst, 1 + asnd + afst + k)

main =
	do [n, k] <- map readInt . BS.words <$> BS.getLine
	   arr <- map readInt64 . BS.words <$> BS.getLine
	   putStrLn $ show' (solve arr k)
	     where show' (a, b) = show a ++ " " ++ show b


import Data.List
import qualified Data.Map as Map

main=do
     a<-getLine
     b<-getLine
     let xs=map read (words b)::[Int]
         ys=sort xs
         l=(length ys)-1
     print $  ys!!(l `div` 2)

import Data.List
main = interact $ show . solve . map read . words
solve (n:as) = sort as !! ((n - 1) `div` 2)

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

main = do
		t<- read <$> getLine ::IO Int
		a<- sort <$> map read <$> words <$> getLine::IO [Int]
		print $ if odd t then a!!(div t 2) else a!!((div t 2)-1)

import Data.List

main :: IO ()
main = do
  n <- getLine
  a <- getLine
  print $ w $ sort $ map read $ words a
  where
    w :: [Int] -> Int
    w a = a !! ((length a - 1) `quot` 2)

--ghc 7.10

import Data.List(sort)

midNumber :: (Ord a) => [a] -> a
midNumber xs = (!! ((length xs - 1) `div` 2)) . sort $ xs

main = do
    nStr <- getLine
    aStrs <- getLine
    let a = map read . words $ aStrs :: [Int]
    print $ midNumber a

{-# Language BangPatterns, ViewPatterns #-}
import Control.DeepSeq
import Data.List
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set

main = do
    n <- fmap readInt $ getLine
    ps <- fmap parseInput $ getLine
    putStrLn $ show $ (sort ps) !! ((n-1)`div`2)

parseInput = map readInt . words
readInt x = (read x) :: Int

import Data.List
import Data.List.Split

main = do
    nstr <- getLine
    let n = read nstr :: Int
    line <- getLine
    let ints = map (read::String->Int) $ splitOn " " line
    let sints = sort ints
    putStrLn.show $ sints !! ((n - 1) `div` 2)

import Data.List
import Data.List.Split

main = do
    nstr <- getLine
    let n = read nstr :: Int
    line <- getLine
    let ints = map (read::String->Int) $ splitOn " " line
    --print ints
    putStrLn.show $ (ints!!(div n 2))

import Data.List
import Data.List.Split

main = do
    nstr <- getLine
    let n = read nstr :: Int
    line <- getLine
    let ints = map (read::String->Int) $ splitOn " " line
    --print ints
    putStrLn.show $ ((sort ints)!!(div n 2))

import Data.List
import Data.List.Split

main = do
    nstr <- getLine
    let n = read nstr :: Int
    line <- getLine
    let ints = map (read::String->Int) $ splitOn " " line
    --print ints
    putStrLn.show $ (sort ints)!! (n - 1) `div` 2

--ghc 7.10

import Data.List(sort)

midNumber :: (Ord a) => [a] -> a
midNumber xs = (!! ((length xs) `div` 2)) . sort $ xs

main = do
    nStr <- getLine
    aStrs <- getLine
    let a = map read . words $ aStrs :: [Int]
    print $ midNumber a


import Control.Monad
import Data.List
import Data.Bits
import Data.Int

c2 :: Int -> Int64
c2 v = let  v2 = fromIntegral v  in  div (v2 * (v2 - 1)) 2

solve :: [Int] -> Int64
solve li = let
  sli = group $ sort [countLeadingZeros x | x <- li, x > 0]
  in  sum $ map (c2 . length) sli

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _n <- getLine
    a <- map read . words <$> getLine
    print $ solve a

import Control.Monad
import Control.Monad.ST
import Data.Array
import qualified Data.Array.ST.Safe as S
import qualified Data.Array.Unboxed as U
import Data.Foldable
import Data.List

lbit :: Int -> Int
lbit x
  | x == 0 = 0
  | otherwise = lbit (x `div` 2) + 1

solve' [] = (0, 0)
solve' [x] = (1, 0)
solve' (a : b : xs) =
  if a == b
    then (\(x, y) -> (x + 1, y)) next
    else (\(x, y) -> (1, y + (x * (x - 1) `div` 2))) next
  where
    next = solve' (b : xs)

solve v = f $ solve' v
  where
    f = (\(a, b) -> b + (a * (a - 1) `div` 2))

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _ <- getLine
    v <- sort . map (lbit . read) . words <$> getLine
    print $ solve v


import Data.Ratio
import Data.Maybe
import Data.Set hiding (map)
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  (_:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) $ C.getContents
  let f (0:_:t) = f t
      f (k:b:t) = b%k: f t
      f _       = []
  print $ size $ fromList $ f $ map toInteger a

import Data.Ratio
import Data.Char
import qualified Data.Map as Map
p[k,b]=((-b)%k,abs k)
s=length . filter ((/=0) . snd) . Map.toList . Map.fromListWith (+)
rd ('-':t) = - rd t
rd x = fromIntegral $ foldl (\x c -> (+ (ord c - ord '0')).(*10) $ x) 0 x :: Integer
main=interact$show.s.map p.filter((/=0).head).map(map rd.words).tail.lines

import Data.Ratio
import Data.Maybe
import Data.Set hiding (map)
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  (_:a) <- fmap (map (fst . fromJust . C.readInteger) . C.words) $ C.getContents
  let f (0:_:t) = f t
      f (k:b:t) = b%k: f t
      f _       = []
  print $ size $ fromList $ f a

import Data.Ratio
import Data.Maybe
import Data.Set hiding (map)
import qualified Data.ByteString.Char8 as C

main = do
  (_:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) $ C.getContents
  let f (0:_:t) = f t
      f (k:b:t) = b%k: f t
      f _       = []
  print $ size $ fromList $ f a

import Data.Ratio
import Data.Char
import qualified Data.Map as Map
p[k,b]=((-b)%k,abs k)
s=length . filter ((/=0) . snd) . Map.toList . Map.fromListWith (+) -- foldr (\(k,v) -> Map.insertWith'(+) k v) Map.empty
rd ('-':t) = - rd t
rd x = foldl (\x c -> (+ (ord c - ord '0')).(*10) $ x) 0 x
main=interact$show.s.map p.filter((/=0).head).map(map rd.words).tail.lines


module Main where

mm :: Integer
mm = 998244353

(|>) = flip (.)

mulmod :: Integer -> Integer -> Integer
mulmod x y = rem (x * y) mm

fexp x 0 = 1
fexp x e | even e = k
         | otherwise = mulmod x k
         where k' = fexp x (e `div` 2)
               k  = mulmod k' k'

inv :: Integer -> Integer
inv x = fexp x (mm-2)

inv100 = inv 100

solve :: [Integer] -> Integer
solve ps = mulmod (solveNum ps) (inv $ solveDen ps)

solveNum :: [Integer] -> Integer
solveNum ps = solveNum' ps 1
    where solveNum' (p:[]) x = x
          solveNum' (p:ps) x = rem (x + (solveNum' ps (mulmod x p))) mm

solveDen :: [Integer] -> Integer
solveDen ps = foldr mulmod 1 ps

main = interact $
    lines |> drop 1 |> map (words |> map read |> map (* inv100) |> solve |> show) |> unlines

module Main where

mm :: Integer
mm = 998244353

(|>) = flip (.)

(*.) x y = rem (x * y) mm
(+.) x y = rem (x + y) mm

fexp x 0 = 1
fexp x e | even e = k
         | otherwise = x *. k
         where k' = fexp x (e `div` 2)
               k  = k' *. k'

inv :: Integer -> Integer
inv x = fexp x (mm-2)

inv100 = inv 100

solve :: [Integer] -> Integer
solve ps = (solveNum ps) *. (inv $ solveDen ps)

solveNum :: [Integer] -> Integer
solveNum ps = solveNum' ps 1
    where solveNum' (p:[]) x = x
          solveNum' (p:ps) x = x +. (solveNum' ps (x *. p))

solveDen = foldr (*.) 1

solveLine = words |> map read |> map (* inv100) |> solve

main = interact $
    lines |> drop 1 |> map (show . solveLine) |> unlines


main=getContents>>=putStrLn.unwords.map show.f.map read.words
f(n:a:x)=[d-min d(a-n+1)+max 1(a-sum x+d)-1|d<-x]

main :: IO ()
main = getContents >>= putStrLn . unwords . map show . solve . map read . words

solve :: [Integer] -> [Integer]
solve (n:a:ds) = [ d - min d (a - n + 1) + max 1 (a - sum ds + d) - 1 | d <- ds ]
solve _ = undefined

import Control.Applicative

solve :: [Integer] -> Integer -> [Integer]
solve ds a = map go ds
  where
    go d = d - (myMax - myMin) - 1
      where
        myMin = max 1 $ a - (max' - d)
        myMax = min d $ a - min' + 1
    min' = toInteger $ length ds
    max' = sum ds

main :: IO ()
main = do
  [n, a] <- map read <$> words <$> getLine
  ds <- map read <$> words <$> getLine
  putStrLn . unwords . map show $ solve ds a

import Control.Applicative

solve :: [Int] -> Int -> [Int]
solve ds a = map go ds
  where
    go d = d - (myMax - myMin) - 1
      where
        myMin = max 1 $ a - (max' - d)
        myMax = min d $ a - min' + 1
    min' = length ds
    max' = sum ds

main :: IO ()
main = do
  [n, a] <- map read <$> words <$> getLine
  ds <- map read <$> words <$> getLine
  putStrLn . unwords . map show $ solve ds a


main :: IO()
main = putStrLn . unwords . map show . proof . solve . map read . words =<< getLine

proof :: [Integer] -> [Integer]
proof [] = [-1]
proof x = x

solve :: [Integer] -> [Integer]
solve [l, r, k] = solve' 1
    where solve' :: Integer -> [Integer]
          solve' x | x < l = solve' (x * k)
                   | x > r = []
                   | otherwise = x : solve' (x * k)

    main = do
        line <- getLine
        let l:r:k:xs = getInts 3 line
        let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)
        putStrLn $ unwords $ ans $ map show [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]

    getInts :: Int -> String -> [Integer]

    getInts 0 _ = []
    getInts _ [] = []
    getInts x str = map stringToInt $ take x $ words str

    stringToInt :: String -> Integer

    stringToInt str = read str :: Integer

    ans [] = ["-1"]
    ans x = x

module Main where

getRangePowers :: Integer -> Integer -> Integer -> [Integer]
getRangePowers l r k = [k ^ a | a <- [0 .. (ceiling ((logBase (fromIntegral k) (fromIntegral r)) :: Float))], k^a >= l, k^a <=r]

emptytoneg [] = [-1]
emptytoneg xs = xs

main = do
        line <- getLine
        let ws = words line
        let l = read (ws !! 0)
        let r = read (ws !! 1)
        let k = read (ws !! 2)
        let powers = getRangePowers l r k
        putStrLn $ unwords $ map show $ emptytoneg powers

import Control.Applicative
import Data.List

main= do
	[l,r,k]<-   map read.words  <$> getLine::IO [Integer]
	let x =   takeWhile (<=r) $ dropWhile (<l) [k^i|i<-[0..]]
	if x==[] then print (-1) else putStrLn $ intercalate " " $ map show x

-- module Main where

-- import Control.Applicative

-- main :: IO ()
-- main = do
--     [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
--     let top = ceiling $ logBase (fromIntegral k) (fromIntegral r)
--         result = [res | n <- [0, 1 .. top], let res = k^n, res >= l, res <= r]
--     if null result
--         then putStrLn "-1"
--         else putStrLn $ unwords $ map show result

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

getIntList :: IO [Integer]
getIntList = fmap read . words <$> getLine

out :: Show a => [a] -> IO ()
out as = putStrLn $ bool (unwords $ map show as) "-1" (null as)

main :: IO ()
main = out =<< sol <$> getIntList

sol :: Integral a => [a] -> [a]
sol [l,r,k] = takeWhile (<=r) . dropWhile (<l) $ fmap (k^) [ll..rr]
  where
      ll = round $ log (fromIntegral l)/log (fromIntegral k)
      rr = round $ log (fromIntegral r)/log (fromIntegral k)

module Main where

calc :: (Integer, Integer, Integer, Integer) -> [Integer]
calc (a, b, k, cur)
         | cur > b = []
         | cur >= a = [cur]++calc(a, b, k, cur*k)
         | otherwise = calc(a, b, k, cur*k)

emptytoneg :: [Integer] -> [Integer]
emptytoneg [] = [-1]
emptytoneg xs = xs

main = do
        args <- getContents
        let
            (l:r:k:xs) = words args
        putStrLn $ unwords $ map show $ emptytoneg $ calc(read l, read r, read k, 1)

import Data.Functor
import Data.List

getIntegers :: IO [Integer]
getIntegers = map read <$> words <$> getLine

parsePairs [] = []
parsePairs (x:y:rs) = (x, y) : parsePairs rs

solve :: Integer -> Integer -> Integer -> [Integer]
solve l r k = takeWhile (<=r) $ dropWhile (<l) $ iterate (*k) 1

main = do
    [l, r, k] <- getIntegers
    putStrLn $ let xs = solve l r k in
        if null xs then "-1" else intercalate " " (map show $ xs)

main = do
    line <- getLine
    let l:r:k:xs = getInts 3 line
    let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)
    putStrLn $ foldr1 (++) $ ans $ map ((' ':) . show) [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]

getInts :: Int -> String -> [Integer]

getInts 0 _ = []
getInts _ [] = []
getInts x str = map stringToInt $ take x $ words str

stringToInt :: String -> Integer

stringToInt str = read str :: Integer

ans [] = ["-1"]
ans y = y

main = do
        line <- getLine
        let l:r:k:xs = getInts 3 line
        let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)
        putStrLn $ unwords $ ans $ map show [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]

getInts :: Int -> String -> [Integer]

getInts 0 _ = []
getInts _ [] = []
getInts x str = map stringToInt $ take x $ words str

stringToInt :: String -> Integer

stringToInt str = read str :: Integer

ans [] = ["-1"]
ans y = y

main = do
	line <- getLine
	let l:r:k:xs = getInts 3 line
	let br = ceiling $ logBase (fromIntegral k) (fromIntegral r)
	putStrLn $ foldr1 (++) $ ans $ map ((' ':) . show) [p | x <- [0,1..br], let p = k^x, p >= l, p <= r]

getInts :: Int -> String -> [Integer]

getInts 0 _ = []
getInts _ [] = []
getInts x str = map stringToInt $ take x $ words str

stringToInt :: String -> Integer

stringToInt str = read str :: Integer

ans [] = ["-1"]
ans x = x

module Main where

import Control.Applicative

f l r k acc n
    | res < l = f l r k acc (n+1)
    | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)
    | otherwise = acc
        where res = k^n

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let result = f l r k [] 0
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

import Control.Applicative

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let top = ceiling $ logBase (fromIntegral k) (fromIntegral r)
        result = [res | n <- [0, 1 .. top], let res = k^n, res >= l, res <= r]
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

import Control.Applicative

f l r k acc n
    | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)
    | otherwise = acc
        where res = k^n

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let result = f l r k [] 0
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

import Control.Applicative

f :: Int -> Int -> Int -> [Int] -> Integer -> [Int]
-- f :: (Num a, Num b) => a -> a -> a -> [a] -> b -> [a]
f l r k acc n
    | res < l = f l r k acc (n+1)
    | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)
    | otherwise = acc
        where res = k^n

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let result = f l r k [] 0
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

import Control.Applicative

f l r k acc n
    | res < l = f l r k acc (n+1)
    | res >= l && res <= r = f l r k (acc ++ [res]) (n+1)
    | res > r = acc
        where res = k^n

main :: IO ()
main = do
    [l, r, k] <- (map (\s -> read s::Int) . words) <$> getLine
    let result = f l r k [] 0
    if null result
        then putStrLn "-1"
        else putStrLn $ unwords $ map show result

module Main where

calc :: (Int, Int, Int, Int) -> [Int]
calc (a, b, k, cur)
         | cur > b = []
         | cur >= a = [cur]++calc(a, b, k, cur*k)
         | otherwise = calc(a, b, k, cur*k)

emptytoneg :: [Int] -> [Int]
emptytoneg [] = [-1]
emptytoneg xs = xs

main = do
        args <- getContents
        let
            (l:r:k:xs) = words args
        putStrLn $ unwords $ map show $ emptytoneg $ calc(read l, read r, read k, 1)

import Data.Functor
import Data.List

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

parsePairs [] = []
parsePairs (x:y:rs) = (x, y) : parsePairs rs

solve :: Int -> Int -> Int -> [Int]
solve l r k = takeWhile (<=r) $ dropWhile (<l) $ iterate (*k) 1

main = do
    [l, r, k] <- getInts
    putStrLn $ let xs = solve l r k in
        if null xs then "-1" else intercalate " " (map show $ xs)

import Control.Applicative

main= do
	[l,r,k]<-   map read.words  <$> getLine::IO [Int]
	let x =  length $takeWhile (<=r) $ dropWhile (<l) [k^i|i<-[1..]]
	print $ if x==0 then (-1) else x

import Control.Applicative
import Data.List

main= do
	[l,r,k]<-   map read.words  <$> getLine::IO [Int]
	let x =   takeWhile (<=r) $ dropWhile (<l) [k^i|i<-[0..]]
	if x==[] then print (-1) else putStrLn $ intercalate " " $ map show x


import Control.Monad (replicateM_)
import Data.List (sort)
main = read <$> getLine >>= flip replicateM_ scase
readI :: IO [Int]
readI = map read . words <$> getLine
scase = read <$> getLine >>=
        \n -> readI >>= \as -> readI >>= \bs -> print (maxDamage n as bs)

maxDamage :: Int -> [Int] -> [Int] -> Int
maxDamage n as bs = let (fires, ices) = partition as bs ([], [])
                        fl = length fires
                        il = length ices
                        (a, al, b, bl) = case compare fl il of
                                           EQ -> (ices, il, fires, fl)
                                           LT -> (ices, il, fires, fl)
                                           GT -> (fires, fl, ices, il)
                        partition [] [] (fs, is) = (reverse (sort fs), reverse (sort is))
                        partition (0:as) (f:bs) (fires, ices) =
                          partition as bs (f:fires, ices)
                        partition (1:as) (i:bs) (fires, ices) =
                          partition as bs (fires, i:ices)

                    in
                      if (al == bl)
                      then 2*(sum a + sum b) - minimum (a++b)
                      else let xs = take (al-1) a
                               x = last a
                           in
                             2*(sum b + sum (take bl xs)) + x + sum (drop bl xs)

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

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

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1 ..] >>> map (uncurry output) >>> C.unlines

data TC = TC {n :: Int, as :: [Int], bs :: [Int64]}

type Output = Int64

input :: Scanner TC
input = do
  n <- int
  as <- n >< int
  bs <- n >< int64
  return TC {..}

solve :: TC -> Output
solve TC {..} = sum bs + extra fire frost + extra frost fire - too_much
  where
    [fire, frost] = [sort [x | (t', x) <- zip as bs, t' == t] | t <- [0, 1]]
    extra xs ys = xs >$> reverse >>> take (length ys) >>> sum
    too_much
      | length fire == length frost = minimum bs
      | otherwise = 0

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

-------------------------- Template ------------------------------------------
-- Debug
debug :: Show a => a -> a

#ifdef ONLINE_JUDGE
debug = id
#else
debug a = trace (show a) a
#endif

-- helpers
(>$>) = flip ($)

infixl 0 >$>

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

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

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

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

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

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

-- Scanner
type Scanner = State [C.ByteString]

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

import Control.Monad
import Data.List

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
        input <- getLine
        let b = map read . words $ input ::[Int]
        let a1 = sortBy (flip compare) . map snd .filter ((0==).fst) .zip a $ b
        let a2 = sortBy (flip compare) . map snd .filter ((1==).fst) .zip a $ b
        let mi = min (length a1) (length a2)
        let s1 = (sum $ zipWith (\x y -> 2*(x+y)) a1 a2)
        let s2 = (sum.drop mi $ a1) + (sum.drop mi $ a2)
        putStrLn .show. (s1+) $ if s2==0 then negate .minimum$ b else s2
    return ()


main = interact solve
solve input = output where
  n = read input :: Int
  output = unlines $ (show $ length xs):xs where
    xs = map (out2.partition) $ codes n
  codes 1 = [ [0] ]
  codes x = concat [ [s++[j]|j<-(xs i s)] | (i,s) <- (zip [1..] (codes (x-1)))]
    where
      xs y z = if odd y then (0:[m,m-1..1]) else ([1..m]++[0])
        where m = foldl1 max z + 1
  partition xs = [[y|(y,z)<-zip [1..] xs,z==x]|x<-[0..foldl1 max xs]]
  out1 [x] = (show x) ++ "}"
  out1 (x:xs) = (show x) ++ "," ++ (out1 xs)
  out2 [x] = '{':(out1 x)
  out2 (x:xs) = (out2 [x]) ++ "," ++ (out2 xs)


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

inf = 10 ^ 18

main = do
    _ <- getLine
    x <- sort . map read . words <$> getLine :: IO [Integer]
    y <- ((-inf) : ) . (++ [inf]) . sort . map read . words <$> getLine :: IO [Integer]
    print $ solve x y

solve [] _ = 0
solve (x:xs) (y1:y2:ys)
    | y2 < x    = solve (x:xs) (y2:ys)
    | otherwise = max (min (x - y1) (y2 - x)) (solve xs (y1:y2:ys))

import Data.Maybe
import Data.Array
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
--import Debug.Trace

getInt = read `fmap` getLine :: IO Int
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]

main = do
    [n, m] <- getInts
    cities <- getInts
    towers <- getInts
    let thresholds = if m == 1 then listArray (1,1) [1000000000 + 1] else listArray (1,m-1) (getThresholds towers) :: Array Int Int
    let towers' = listArray (1,m) towers
    print $ solve thresholds towers' cities

getThresholds :: [Int] -> [Int]
getThresholds towers = zipWith (\x y -> (x + y) `div` 2) towers (tail towers)

solve thresholds towers cities = f cities 0 where
    numThresholds = length (elems thresholds)
    f [] soln = soln
    f (x:xs) soln = f xs (max (abs (nearest x - x)) soln)
    nearest x = towers ! (bin x 1 numThresholds)
    bin x i j
        | x > thresholds ! j        = j + 1
        | i >= j                    = j
        | thresholds ! mid == x     = mid
        | thresholds ! mid > x      = bin x i mid
        | otherwise                 = bin x (mid+1) j
        where mid = (i + j) `div` 2


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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [hh, mm] <- getInts
    [h0, m0] <- map (fst . fromJust . C.readInt) . C.split ':' <$> C.getLine
    let
      rev '0' = Just '0'
      rev '1' = Just '1'
      rev '2' = Just '5'
      rev '5' = Just '2'
      rev '8' = Just '8'
      rev _ = Nothing
      revTwo [c1, c2] = do
        c1' <- rev c1
        c2' <- rev c2
        return [c2', c1']
      revTime h m = do
        s' <- revTwo $ printf "%02d" h
        t' <- revTwo $ printf "%02d" m
        guard $ read t' < hh && read s' < mm
        return $ printf "%02d" h ++ ":" ++ printf "%02d" m
      toRev o = revTime h' m'
        where
        o' = o `mod` (hh * mm)
        h' = o' `quot` mm
        m' = o' `mod` mm
      result = fromJust $ toRev $ head $ filter (isJust . toRev) [h0 * mm + m0 .. ]
    C.putStrLn $ C.pack result

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

-- http://codeforces.com/contest/1493/problem/B   (mirror clock)

import qualified Data.List as List

import Text.Printf (printf)

main = interact $ unlines . map solveTC . linePairs . tail . lines

solveTC (hh, mm, strTime) = goodStrTime
  where
    (Just goodStrTime) = (List.find isGoodStrTime . map toStrTime) [toMinutes strTime ..]

    isGoodStrTime tm
        | '?' `elem` rev     = False
        | hours   rev >= hh  = False
        | minutes rev >= mm  = False
        | otherwise          = True
      where
        rev = (map mirrorChar . reverse) tm

    toMinutes tm = minutes tm + (mm * hours tm)

    toStrTime tmMinutes = printf "%02d:%02d" (m `div` mm) (m `mod` mm)
      where
        m = tmMinutes `mod` (hh * mm)

hours   [ hiH,  loH, ':', _hiM, _loM] = readI [hiH, loH]
minutes [_hiH, _loH, ':',  hiM,  loM] = readI [hiM, loM]

mirrorChar = f
  where
    f '0' = '0'
    f '1' = '1'
    f '2' = '5'
    f '5' = '2'
    f '8' = '8'
    f ':' = ':'
    f _ch = '?'

linePairs [] = []
linePairs [_line] = error "bad input (no pair)"
linePairs (strHM:strTime:ls) = (hh, mm, strTime) : linePairs ls
  where
    [hh, mm] = (map readI . words) strHM

readI s = read s :: Int

module Main where

import Control.Monad
import Data.Maybe

main :: IO ()
main = do
    n <- ((read :: String -> Int) <$> getLine)
--    putStrLn (show n)
    replicateM_ n action

action :: IO ()
action = do
    [h, m] <- (map (read :: String -> Int) . words) <$> getLine
    time <- getLine
    let res = dropWhile (not . mirror h m) (flow h m time)
    putStrLn $ head res

flow :: Int -> Int -> String -> [String]
flow h m initial@([h1,h2,_,m1,m2]) = map (\(_, _, r) -> r) $ iterate inc (read [h1,h2], read [m1,m2], initial)
  where
    show2 x
        | x < 10 = '0':show x
        | otherwise = show x
    showTime ch cm = show2 ch ++ ':' : show2 cm
    maxM = m - 1
    maxH = h - 1
    inc :: (Int, Int, String) -> (Int, Int, String)
    inc (ch, cm, _)
        | cm < maxM = (ch, cm + 1, showTime ch (cm + 1))
        | ch < maxH = (ch + 1, 0, showTime (ch + 1) 0)
        | otherwise = (0, 0, "00:00")

mirror :: Int -> Int -> String -> Bool
mirror h m time = fromMaybe False (checkTime <$> (mir time))
  where
    checkTime :: String -> Bool
    checkTime (m2:m1:_:h2:h1:[]) = (read [h1,h2]) < h && (read [m1,m2]) < m
    mir :: String -> Maybe String
    mir s = mapM mi s
    mi :: Char -> Maybe Char
    mi c = case c of
        '0' -> Just c
        '1' -> Just c
        '8' -> Just c
        ':' -> Just c
        '2' -> Just '5'
        '5' -> Just '2'
        otherwise -> Nothing

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [hh, mm] <- getInts
    [h0, m0] <- map (fst . fromJust . C.readInt) . C.split ':' <$> C.getLine
    let
      rev '0' = Just '0'
      rev '1' = Just '1'
      rev '2' = Just '2'
      rev '5' = Just '5'
      rev '8' = Just '8'
      rev _ = Nothing
      revTwo [c1, c2] = do
        c1' <- rev c1
        c2' <- rev c2
        return [c2', c1']
      revTime h m = do
        s' <- revTwo $ printf "%02d" h
        t' <- revTwo $ printf "%02d" m
        guard $ read t' < hh && read s' < mm
        return $ printf "%02d" h ++ ":" ++ printf "%02d" m
      toRev o = revTime h' m'
        where
        o' = o `mod` (hh * mm)
        h' = o' `quot` mm
        m' = o' `mod` mm
      result = fromJust $ toRev $ head $ filter (isJust . toRev) [h0 * mm + m0 .. ]
    C.putStrLn $ C.pack result


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
import Data.Array.ST
import Control.Monad.ST

import qualified Data.IntSet as S

sieve :: Int -> UArray Int Int
sieve n = accumArray min n (1, n) $ (1, 1) : do
  i <- [2..n]
  zip [i, 2*i .. n] $ repeat i

extractFactors :: UArray Int Int -> Int -> [Int]
extractFactors lpf = let
  go 1 = []
  go x = let  p = lpf ! x  in  p : go (quot x p)
  in  map head . group . go

dsuFind :: STUArray s Int Int -> Int -> ST s Int
dsuFind arr x = do
  p <- readArray arr x
  if  p == x
    then  pure x
    else  do
    p2 <- readArray arr x
    writeArray arr x p2
    dsuFind arr p2

merge :: (Int, Int) -> [(Int, Int)] -> UArray Int Int
merge bnds pairs = runSTUArray $ do
  par <- newListArray bnds $ range bnds
  sz <- newArray bnds 1 :: ST s (STUArray s Int Int)
  forM_ pairs $ \(x, y) -> do
    p <- dsuFind par x
    q <- dsuFind par y
    when (p /= q) $ do
      ps <- readArray sz p
      qs <- readArray sz q
      let  (s, t) = if  ps >= qs  then  (p, q)  else  (q, p)
      writeArray par t s
      writeArray sz s (ps + qs)
  forM_ (range bnds) $ \x -> dsuFind par x >>= writeArray par x
  pure par

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, q] <- readInts
  aLi <- readInts
  let
    a :: UArray Int Int
    a = listArray (1, n) aLi
    m = 1 + foldl' max 1 (elems a)
    lpf = sieve m
    direct :: Array Int [Int]
    direct = accumArray (flip (:)) [] (1, m) $ do
      (i, ai) <- assocs a
      [(p, i) | p <- extractFactors lpf ai]
    components = merge (1, n) [(v1, v2) | v1 : vs <- elems direct, v2 <- vs]
    oneSteps :: Array Int S.IntSet
    oneSteps = accumArray (flip S.insert) (S.empty) (1, m) $ do
      (i, ai) <- assocs a
      let
        js = components ! i : do
          p <- extractFactors lpf (ai + 1)
          j <- take 1 $ direct ! p
          pure $ components ! j
      [(j1, j2) | j1 <- js, j2 <- js]
  replicateM_ q $ do
    [s, t] <- map (components !) <$> readInts
    putInts $ pure $ if  s == t
      then  0
      else  if  S.member s (oneSteps ! t)
      then  1
      else  2

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

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative (liftA2)
import Control.Monad (forM_, guard, replicateM, when)
import Control.Monad.ST (ST, runST)
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Array.IArray (Array, elems)
import Data.Array.ST (MArray (newArray), STUArray, freeze, newListArray, readArray, writeArray)
import Data.Array.Unboxed (UArray, accumArray, (!))
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.IntSet as S
import Data.List (group, sort, unfoldr)
import Data.Maybe (fromJust)
import Debug.Trace (trace)

main :: IO ()
main = C.interact $ runScanner (C.pack <$> testCase)

testCase :: Scanner String
testCase = do
  n <- int
  q <- int
  as <- n >< int
  qs <- q >< pair int int
  return . unlines . map show $ solve n as qs

type VVI = Array Int [Int]
type VSI = Array Int S.IntSet

solve :: Int -> [Int] -> [(Int, Int)] -> [Int]
solve n as = map query
  where
    query (u, v)
      | cu == cv = 0
      | cv `S.member` (adj ! cu) = 1
      | otherwise = 2
      where
        cu = dsu ! u
        cv = dsu ! v

    ps :: VVI
    ps = accumArray' (:) [] (1, lim) $ do
      (a, i) <- zip as [1 .. n]
      (,i) <$> factorize a
    dsu = buildDSU n $ concat [zip xs (tail xs) | xs <- elems ps, not (null xs)]

    adj :: VSI
    adj = accumArray' S.insert S.empty (1, n) $ do
      (a, i) <- zip as [1 .. n]
      let nodes = dsu ! i : [dsu ! head ns | f <- factorize (a + 1),
                                       let ns = ps ! f,
                                       not (null ns)]
      [(u, v) | u <- nodes, v <- nodes]

lim = 1 + 10 ^ 6
primes = sieve lim

factorize :: Int -> [Int]
factorize = map head . group . unfoldr f
  where
    f 1 = Nothing
    f n = let p = primes ! n in Just (p, n `div` p)

accumArray' f = accumArray (flip f)

-------------------------- Template ------------------------------------------
-- sieve
sieve :: Int -> UArray Int Int
sieve n =
  accumArray min n (1, n) $
    (1, 1) : do
      i <- [2 .. n]
      zip [i, 2 * i .. n] $ repeat i

-- DSU --
data DSU s = DSU {parentST :: STUArray s Int Int, sizeST :: STUArray s Int Int}

mkDSU :: Int -> ST s (DSU s)
mkDSU n = DSU <$> newListArray (1, n) [1 .. n] <*> newArray (1, n) 1

find :: Int -> DSU s -> ST s Int
find u dsu@(DSU par _) = do
  p <- readArray par u
  if p == u
    then return u
    else do
      p' <- find p dsu
      writeArray par u p'
      return p'

merge :: Int -> Int -> DSU s -> ST s Bool
merge u v dsu@(DSU par sz) = do
  u <- find u dsu
  v <- find v dsu
  when (u /= v) $ do
    su <- readArray sz u -- su = sz[pu]
    sv <- readArray sz v -- sv = sz[pv]
    let s = su + sv
    let (u', v') = if su >= sv then (u, v) else (v, u)
    writeArray par v' u' -- par[v] = u
    writeArray sz u' s -- sz[u] = s
  return $ u /= v

same :: Int -> Int -> DSU s -> ST s Bool
same u v dsu = (==) <$> find u dsu <*> find v dsu

buildDSU :: Int -> [(Int, Int)] -> UArray Int Int
buildDSU n edges = runST $ do
  dsu <- mkDSU n
  forM_ edges $ \(u, v) -> merge u v dsu
  forM_ [1 .. n] $ \u -> find u dsu
  freeze $ parentST dsu

-- Scanner --
type Scanner = State [C.ByteString]

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative (liftA2)
import Control.Monad (forM_, guard, replicateM, when)
import Control.Monad.ST (ST, runST)
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Array.IArray (Array, elems)
import Data.Array.ST (MArray (newArray), STUArray, freeze, newListArray, readArray, writeArray)
import Data.Array.Unboxed (UArray, accumArray, (!))
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.IntSet as S
import Data.List (group, sort, unfoldr)
import Data.Maybe (fromJust)
import Debug.Trace (trace)

main :: IO ()
main = C.interact $ runScanner (C.pack <$> testCase)

testCase :: Scanner String
testCase = do
  n <- int
  q <- int
  as <- n >< int
  qs <- q >< pair int int
  return . unlines . map show $ solve n as qs

type VVI = Array Int [Int]
type VSI = Array Int S.IntSet

solve :: Int -> [Int] -> [(Int, Int)] -> [Int]
solve n as = map query
  where
    query (u, v)
      | cu == cv = 0
      | cv `S.member` (adj ! cu) = 1
      | otherwise = 2
      where
        cu = dsu ! u
        cv = dsu ! v

    ps :: VVI
    ps = accumArray' (:) [] (1, lim) $ do
      (a, i) <- zip as [1 .. n]
      (,i) <$> factorize a
    dsu = buildDSU n $ concat [zip xs (tail xs) | xs <- elems ps, not (null xs)]

    adj :: VSI
    adj = accumArray' S.insert S.empty (1, n) $ do
      (a, i) <- zip as [1 .. n]
      let nodes = i : [dsu ! head ns | f <- factorize (a + 1),
                                       let ns = ps ! f,
                                       not (null ns)]
      [(u, v) | u <- nodes, v <- nodes]

lim = 10 ^ 6
primes = sieve lim

factorize :: Int -> [Int]
factorize = map head . group . unfoldr f
  where
    f 1 = Nothing
    f n = let p = primes ! n in Just (p, n `div` p)

accumArray' f = accumArray (flip f)

-------------------------- Template ------------------------------------------
-- sieve
sieve :: Int -> UArray Int Int
sieve n =
  accumArray min n (1, n) $
    (1, 1) : do
      i <- [2 .. n]
      zip [i, 2 * i .. n] $ repeat i

-- DSU --
data DSU s = DSU {parentST :: STUArray s Int Int, sizeST :: STUArray s Int Int}

mkDSU :: Int -> ST s (DSU s)
mkDSU n = DSU <$> newListArray (1, n) [1 .. n] <*> newArray (1, n) 1

find :: Int -> DSU s -> ST s Int
find u dsu@(DSU par _) = do
  p <- readArray par u
  if p == u
    then return u
    else do
      p' <- find p dsu
      writeArray par u p'
      return p'

merge :: Int -> Int -> DSU s -> ST s Bool
merge u v dsu@(DSU par sz) = do
  u <- find u dsu
  v <- find v dsu
  when (u /= v) $ do
    su <- readArray sz u -- su = sz[pu]
    sv <- readArray sz v -- sv = sz[pv]
    let s = su + sv
    let (u', v') = if su >= sv then (u, v) else (v, u)
    writeArray par v' u' -- par[v] = u
    writeArray sz u' s -- sz[u] = s
  return $ u /= v

same :: Int -> Int -> DSU s -> ST s Bool
same u v dsu = (==) <$> find u dsu <*> find v dsu

buildDSU :: Int -> [(Int, Int)] -> UArray Int Int
buildDSU n edges = runST $ do
  dsu <- mkDSU n
  forM_ edges $ \(u, v) -> merge u v dsu
  forM_ [1 .. n] $ \u -> find u dsu
  freeze $ parentST dsu

-- Scanner --
type Scanner = State [C.ByteString]

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

import 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
import Data.Array.ST
import Control.Monad.ST

import qualified Data.IntSet as S

sieve :: Int -> UArray Int Int
sieve n = accumArray min n (1, n) $ (1, 1) : do
  i <- [2..n]
  zip [i, 2*i .. n] $ repeat i

extractFactors :: UArray Int Int -> Int -> [Int]
extractFactors lpf = let
  go 1 = []
  go x = let  p = lpf ! x  in  p : go (quot x p)
  in  map head . group . go

dsuFind :: STUArray s Int Int -> Int -> ST s Int
dsuFind arr x = do
  p <- readArray arr x
  if  p == x
    then  pure x
    else  do
    p2 <- readArray arr x
    writeArray arr x p2
    dsuFind arr p2

merge :: (Int, Int) -> [(Int, Int)] -> UArray Int Int
merge bnds pairs = runSTUArray $ do
  par <- newListArray bnds $ range bnds
  sz <- newArray bnds 1 :: ST s (STUArray s Int Int)
  forM_ pairs $ \(x, y) -> do
    p <- dsuFind par x
    q <- dsuFind par y
    when (p /= q) $ do
      ps <- readArray sz p
      qs <- readArray sz q
      let  (s, t) = if  ps >= qs  then  (p, q)  else  (q, p)
      writeArray par t s
      writeArray sz s (ps + qs)
  forM_ (range bnds) $ \x -> dsuFind par x >>= writeArray par x
  pure par

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, q] <- readInts
  aLi <- readInts
  let
    a :: UArray Int Int
    a = listArray (1, n) aLi
    m = 1 + foldl' max 1 (elems a)
    lpf = sieve m
    direct :: Array Int [Int]
    direct = accumArray (flip (:)) [] (1, m) $ do
      (i, ai) <- assocs a
      [(p, i) | p <- extractFactors lpf ai]
    components = merge (1, n) [(v1, v2) | v1 : vs <- elems direct, v2 <- vs]
    oneSteps :: Array Int S.IntSet
    oneSteps = accumArray (flip S.insert) (S.empty) (1, m) $ do
      (i, ai) <- assocs a
      let  ic = components ! i
      p <- extractFactors lpf (ai + 1)
      j <- take 1 $ direct ! p
      let  jc = components ! j
      [(ic, jc), (jc, ic)]
  replicateM_ q $ do
    [s, t] <- map (components !) <$> readInts
    putInts $ pure $ if  s == t
      then  0
      else  if  S.member s (oneSteps ! t)
      then  1
      else  2

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 Control.Monad
import Data.Array.IArray
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Data.Array.MArray.Safe
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

getInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]
parseInt = fst . fromJust . BS8.readInt

type Position = (Int, Int)
type Board = UArray (Int, Int) Bool
type Visible = UArray (Int, Int) Bool

main = do
    [n, m] <- getInts
    board <- toTable n m `fmap` replicateM n getInts
    let actorExists = map (checkExist board n m) [(-1,0), (1,0), (0,-1), (0,1)]
    print $ sum $ map (length . (goodPositions board n m)) actorExists

visitOrder n m dir = case dir of
    (-1,0) -> ([1..n], [1..m])
    (1,0) -> ([1..n], [m,m-1..1])
    (0,-1) -> ([1..n], [1..m])
    (0,1) -> ([n,n-1..1], [1..m])

checkExist :: Board -> Int -> Int -> (Int,Int) -> Visible
checkExist board n m (dirX,dirY) = runSTUArray $ do
    a <- newArray ((1,1),(n,m)) False
    let (rows, cols) = visitOrder n m (dirX,dirY)
    forM_ rows $ \y -> do
        forM_ cols $ \x -> do
            let y' = y + dirY
            let x' = x + dirX
            if 1 <= y' && y' <= n && 1 <= x' && x' <= m
            then do
                prev <- readArray a (y',x')
                writeArray a (y,x) (prev || board ! (y',x'))
            else return ()
    return a

toTable :: Int -> Int -> [[Int]] -> Board
toTable n m board = listArray ((1,1),(n,m)) [x == 1 | row <- board, x <- row]

goodPositions :: Board -> Int -> Int -> Visible -> [Position]
goodPositions board n m good = [(i,j) | i <- [1..n], j <- [1..m], board ! (i,j) == False, good ! (i,j)]

import Control.Monad
import Control.DeepSeq
import Control.Exception
import Data.Array.IArray
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Data.Array.MArray.Safe
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

getInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]
parseInt = fst . fromJust . BS8.readInt

type Position = (Int, Int)
type Board = UArray (Int, Int) Int
type Visible = UArray (Int, Int) Bool

main = do
    [n, m] <- getInts
    board <- toTable n m `fmap` replicateM n getInts
    evaluate board
    let actorExists = map (checkExist board n m) [(-1,0), (1,0), (0,-1), (0,1)]
    print $ sum $ map (length . (goodPositions board n m)) actorExists

visitOrder n m dir = case dir of
    (-1,0) -> ([1..n], [1..m])
    (1,0) -> ([1..n], [m,m-1..1])
    (0,-1) -> ([1..n], [1..m])
    (0,1) -> ([n,n-1..1], [1..m])

checkExist :: Board -> Int -> Int -> (Int,Int) -> Visible
checkExist board n m (dirX,dirY) = runSTUArray $ do
    a <- newArray ((1,1),(n,m)) False
    let (rows, cols) = visitOrder n m (dirX,dirY)
    forM_ rows $ \y -> do
        forM_ cols $ \x -> do
            let y' = y + dirY
            let x' = x + dirX
            if 1 <= y' && y' <= n && 1 <= x' && x' <= m
            then do
                prev <- readArray a (y',x')
                writeArray a (y,x) (prev || board ! (y',x') == 1)
            else return ()
    return a
{-
checkExist board n m (dirX,dirY) = a where
    a = array ((1,1),(n,m)) [((i,j), force $ check i j) | i <- [1..n], j <- [1..m]]
    check i j
        | valid i' j' = a ! (i',j') || board ! (i',j') == 1
        | otherwise = False
        where
            valid i j = 1 <= i && i <= n && 1 <= j && j <= m
            i' = i + dirY
            j' = j + dirX
-}

toTable :: Int -> Int -> [[Int]] -> Board
toTable n m board = listArray ((1,1),(n,m)) [x | row <- board, x <- row]

goodPositions :: Board -> Int -> Int -> Visible -> [Position]
goodPositions board n m good = [(i,j) | i <- [1..n], j <- [1..m], board ! (i,j) == 0, good ! (i,j)]