-- http://codeforces.com/problemset/problem/1257/C

import           Control.Monad
import qualified Data.Map      as Map
import           Data.Maybe

type Case = [Int]
type History = Map.Map
data Record = Record { latestIndex   :: Int
                     , minDifference :: Maybe Int
                     } deriving (Show)

filterTestCases :: [String] -> [String]
filterTestCases lines =
  map snd -- get the values of the indexed list = [2]
  $ filter (odd . fst) -- filter the list by odd indices = [(1,2)]
  $ zip [0..] lines -- create an indexed list = [(0,1),(1,2),(2,3)]

toCase :: String -> Case
toCase line = map read $ words line :: Case

updateRecord :: Int -> Int -> Record -> Record
updateRecord key index record
  | minDifference record == Nothing = record { latestIndex = index, minDifference = currentDifference }
  | currentDifference < minDifference record = record { latestIndex = index, minDifference = currentDifference }
  | otherwise = record { latestIndex = index }
  where currentDifference = Just $ index - latestIndex record

updateHistory :: Int -> Int -> History Int Record -> History Int Record
updateHistory key index history
  | Map.notMember key history = Map.insert key Record { latestIndex=index, minDifference=Nothing } history
  | Map.member key history = Map.insert key (updateRecord key index (fromJust $ Map.lookup key history)) history

getMin :: [Maybe Int] -> Maybe Int
getMin []   = Nothing
getMin list = foldr1 min list

solveRecursive :: Case -> Int -> History Int Record -> Maybe Int
solveRecursive [] index history
  | Map.size history == 0 = Nothing
  | otherwise = getMin $ filter isJust $ map minDifference $ Map.elems history
solveRecursive (x:xs) index history =
  solveRecursive xs (index + 1) $ updateHistory x index history

solve :: Case -> Int
solve [] = -1
solve (x:xs)
  | isNothing solution = -1
  | otherwise = 1 + (fromJust solution)
  where solution = solveRecursive xs (index + 1) history
        history = Map.singleton x Record {latestIndex=index, minDifference=Nothing}
        index = 0

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . filterTestCases . tail . lines

import qualified Data.Map as Map
import Data.Maybe
import Control.Monad

type State = (Map.Map Int Index, Maybe Int)
type Indexed a = (Index,a)
type Index = Int

step :: State -> Indexed Int-> State
step (m,Just c) (index,n) = (newMap,Just $ min c d)
  where
    newMap = Map.insert n index m
    d =1+ index - fromMaybe 0 (Map.lookup n m)
step (m, Nothing) (index,n) = (newMap,d)
  where
    newMap = Map.insert n index m
    d =(\x ->1 + index - x) <$> Map.lookup n m

solve :: [Int] -> Maybe Int
solve l = snd $ foldl step (Map.empty,Nothing) (zip [0..] l)

routine :: IO ()
routine = do
   _ <- getLine
   l <- fmap (map read.words) getLine
   print $ fromMaybe (-1) $ solve l

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


module Main where

import Control.Monad
import Prelude

main = do
    getLine
    s <- getLine
    let a = length $ filter (=='A') s
    let b = length $ filter (=='D') s
    if a < b then putStrLn "Danik"
    else if a > b then putStrLn "Anton"
    else putStrLn "Friendship"

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

ans a d | a==d = "Friendship"
	| a>d  = "Anton"
        | otherwise = "Danik"

onecase= do
		x<-getLine
		let a = length $ filter (=='A') x
		let d = length $ filter (=='D') x
		putStrLn $ ans a d

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

anton "" = 0
anton (x:xs) = new + anton xs
    where new = if x == 'A' then 1 else 0

getResult str
    | a > d = "Anton"
    | d > a = "Danik"
    | otherwise = "Friendship"
    where a = anton str
          d = length str - a

main :: IO ()
main = do
    getLine
    ln <- getLine
    putStrLn $ getResult ln

--ghc 7.10

import Data.List

winnerStr = ["Danik","Friendship","Anton"]

result :: Char -> Int
result 'A' = -1
result 'D' = 1
result _ = 0

winner :: [Char] -> String
winner g = (!!) winnerStr . fromEnum . compare 0 . sum . map result $ g

main = do
    nStr <- getLine
    g <- getLine
    putStrLn $ winner g

module Main where

main :: IO ()
main = interact $ f . (\(_:x:_) -> x) . words

f :: String -> String
f xs | length (filter (=='D') xs) *2 > length xs = "Danik"
     | length (filter (=='D') xs) *2 < length xs = "Anton"
     | otherwise = "Friendship"

count :: (Int, Int) -> String -> (Int, Int)
count (a, d) [] = (a, d)
count (a, d) (s:xs)
    | s == 'A' = count ((a + 1), d) xs
    | s == 'D' = count (a, (d + 1)) xs

res :: Int -> Int -> String
res a d
    | a < d = "Danik"
    | a > d = "Anton"
    | otherwise = "Friendship"

main = do
    _ <- getLine
    arr <- getLine

    let (a, d) = count (0, 0) arr
    putStrLn $ res a d

import Control.Applicative
import Data.List

main=do
    n<- read <$> getLine ::IO Int
    a<-   getLine
    let b = length $ filter (=='A') a
    putStrLn $ if b > n-b then "Anton" else if n-b >b then "Danik" else "Friendship"

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

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

whoWon :: String -> String
whoWon s
    | a > d     = "Anton"
    | a < d     = "Danik"
    | otherwise = "Friendship"
        where a = length $ filter (=='A') s
              d = (length s) - a

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

main = interact solve
solve s = case compare a d of
    GT -> "Anton"
    LT -> "Danik"
    EQ -> "Friendship"
  where a = length (filter (== 'A') s)
        d = length (filter (== 'D') s)

main :: IO ()
main = interact (solve . (!! 1) . lines)

solve :: String -> String
solve s
  | a > d = "Anton"
  | a < d = "Danik"
  | a == d = "Friendship"
  where
    a = length . filter (== 'A') $ s
    d = length . filter (== 'D') $ s

-- Vicfred
-- https://codeforces.com/problemset/problem/734/A

solve :: String -> String
solve s
    | a > d     = "Anton"
    | a < d     = "Danik"
    | otherwise = "Friendship"
        where a = length $ filter (=='A') s
              d = (length s) - a

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

-- Vicfred
-- https://codeforces.com/problemset/problem/734/A

solve :: String -> String
solve s
    | a > d     = "Anton"
    | a < d     = "Danik"
    | otherwise = "Friendship"
        where a = length $ filter (=='A') s
              d = (length s) - a

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

{-# LANGUAGE BangPatterns #-}
module Main where

import Control.Applicative

data Result = Anton
            | Danik
            | Friendship
            deriving Show

solve :: String -> Result
solve input = go input 0 0
    where
        go [] !a !d
            | a > d = Anton
            | a < d = Danik
            | otherwise = Friendship

        go ('A':cs) !a !d = go cs (a+1) d
        go ('D':cs) !a !d = go cs a (d+1)

main :: IO ()
main = do
    _ <- getLine
    putStrLn =<< (show . solve) <$> getLine

import Data.List
solve = p . (\(x, y) -> (length x, length y)) . partition (== 'A')
p (a,d) | a > d = "Anton"
        | a < d = "Danik"
        | otherwise = "Friendship"
main = interact $ solve . (!! 1) . lines

toint :: String -> Int
toint n = read n

isA :: Char -> Int
isA 'A' = 1
isA 'D' = 0

count :: String -> Int
count [] = 0
count (x:xs) = isA x + count xs

main = do
    input <- getLine
    let n = toint input
    input <- getLine
    let s = input
    let a = count s
        b = n - a
    if a>b then
        putStrLn("Anton")
    else if a<b then
        putStrLn("Danik")
    else
        putStrLn("Friendship")

isWinner :: String -> (Int, Int) -> (Int, Int)
isWinner [] acc = acc
isWinner (x:xs) (a,b) =
    case x of
        'A' -> isWinner xs (a + 1, b)
        'D' -> isWinner xs (a, b + 1)
resWin :: (Int, Int) -> String
resWin (x,y)
    | (x > y) = "Anton"
    | (x == y) = "Friendship"
    | otherwise = "Danik"
main = do
    a <- getLine
    b <- getLine
    res <- return $ isWinner b (0,0)
    putStrLn $ resWin res

module Main where

main :: IO ()
main = do
  _    <- getLine
  line <- getLine
  let aCount = length $ filter (== 'A') line
  let dCount = length line - aCount
  if aCount > dCount
    then putStrLn "Anton"
    else if dCount > aCount then putStrLn "Danik" else putStrLn "Friendship"

module Main where

process :: (Ord a, Num a) => String -> a -> a -> String
process [] aCount dCount | aCount > dCount = "Anton"
                         | dCount > aCount = "Danik"
                         | otherwise       = "Friendship"
process line aCount dCount
  | head line == 'A' = process (tail line) (aCount + 1) dCount
  | head line == 'D' = process (tail line) aCount (dCount + 1)

main :: IO ()
main = do
  _    <- getLine
  line <- getLine
  putStrLn $ process line 0 0
  return ()

module Main where

main :: IO ()
main = do
  getLine
  line <- getLine
  let aCount = length $ filter (== 'A') line
  let dCount = length line - aCount
  putStrLn $ process aCount dCount
 where
  process aCount dCount | aCount > dCount = "Anton"
                        | dCount > aCount = "Danik"
                        | otherwise       = "Friendship"

module Main where

main :: IO ()
main = do
  getLine
  line <- getLine
  let aCount = length $ filter (== 'A') line
  let dCount = length line - aCount
  if aCount > dCount
    then putStrLn "Anton"
    else if dCount > aCount then putStrLn "Danik" else putStrLn "Friendship"

citesc_nr :: String -> Int
citesc_nr s = read s
main = do
    x <- getLine
    let n = (citesc_nr x)
    sir <- getLine
    let anton = length $ filter (== 'A') sir
    let danik = length $ filter (== 'D') sir
    putStrLn $ solve anton danik
solve x y
    | x==y = "Friendship"
    | x>y = "Anton"
    | otherwise = "Danik"

-- Codeforces Round #379 (Div. 2)
-- http://codeforces.com/contest/734

-- ID: 734A (Anton and Danik)

main = do
    n <- read `fmap` getLine :: IO Int
    s <- getLine
    let anton = length $ filter (== 'A') s
    let danik = length $ filter (== 'D') s
    if anton == danik
    then putStrLn "Friendship"
    else if anton > danik
    then putStrLn "Anton"
    else putStrLn "Danik"

module Main
    where

import System.IO

count ws =
    count' 0 0 ws
    where
        count' a d [] =
            (a, d)
        count' a d (w:ws) =
            if w == 'A' then
                count' (a + 1) d ws
            else
                count' a (d + 1) ws

solve ws =
    case count ws of
        (a, d) ->
            if a < d then
                "Danik"
            else if a == d then
                "Friendship"
            else
                "Anton"

main = do
    first <- getLine
    second <- getLine
    putStrLn $ solve second

import Control.Monad

sol :: String -> Int -> Int -> String
sol [] a b = if (a > b) then "Anton"
  else if (b > a) then "Danik"
  else "Friendship"

sol games one two = if (head games) == 'A'
  then (sol (tail games) (one + 1) two)
  else (sol (tail games) one (1 + two))

main :: IO ()
main = do
  n_s <- getLine
  let n = read n_s :: Int
  inputs <- getLine :: IO String
  putStrLn (sol inputs 0 0)

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

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

main = do
	getLine
	s <- getLine
	let
		a = f 'A' s
		d = f 'D' s
	putStrLn $ solve a d

f c = length . filter ( == c )

solve a d
	| a > d = "Anton"
	| a < d = "Danik"
	| otherwise = "Friendship"

solve :: String -> String
solve games = if (length $ filter (\x -> x == 'A') games) > (length $ filter (\x -> x == 'D') games)
    then "Anton"
    else if (length $ filter (\x -> x == 'A') games) < (length $ filter (\x -> x == 'D') games)
        then "Danik"
        else "Friendship"

main :: IO ()
main = do
    games <- getLine
    games <- getLine

    putStrLn $ solve games

f :: Integer -> Char -> Integer
f t a =
 if a == 'A' then t + 1 else t - 1

main = do
 ni <- getLine
 let n = (read ni :: Integer)
 name <- getLine
 let ans = foldl f 0 name
 putStrLn (
  if ans < 0 then "Danik"
  else if ans > 0 then "Anton"
  else "Friendship")

what a b
  | a > b = "Anton"
  | b > a = "Danik"
  | a == b = "Friendship"

chess lst a d
  | (null lst) = what a d
  | (head lst) == 'A' = chess (tail lst) (a+1) d
  | (head lst) == 'D' = chess (tail lst) a (d+1)

main = do
  ss <- getLine
  ll <- getLine
  let ans = chess ll 0 0
  putStrLn ans

import Control.Monad
import Data.Array
import Data.Char
import Data.Functor
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import qualified Data.ByteString.Char8 as B

solve :: (Ord a) => a -> a -> String
solve x y
    | x > y = "Anton"
    | x < y = "Danik"
    | x == y = "Friendship"

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

main :: IO ()
main = do
    n <- getLine
    s <- getLine
    let countA = count 'A' s
        countD = count 'D' s
    putStrLn $ solve countA countD

main = do
  c <- getContents
  let lns = lines c
  let s = lns!!1
  let a = [ x | x <- s, x == 'A']
  let d = [ x | x <- s, x == 'D']
  let cmp = (length a) `compare` (length d)
  case cmp of
    LT -> putStrLn "Danik"
    EQ -> putStrLn "Friendship"
    _ -> putStrLn "Anton"

tores (a,b)
  | a==b = "Friendship"
  | a>b = "Anton"
  | a<b = "Danik"
solve s = (length $ filter (=='A') s, length $ filter (=='D') s)
main = interact $ tores . solve . head . tail . lines

import System.Environment
import Control.Monad

main :: IO ()
main = do
  [_, s] <- replicateM 2 getLine
  let as = length $ filter (=='A') s
  let ds = length $ filter (=='D') s
  if as > ds then putStrLn "Anton"
    else if as < ds then putStrLn "Danik"
    else putStrLn "Friendship"

import System.IO

solve :: String -> String
solve s =
  let a = length $ filter (=='A') s
      d = length $ filter (=='D') s
  in case a `compare` d of
       GT -> "Anton"
       EQ -> "Friendship"
       LT -> "Danik"

main = do
  getLine
  putStrLn =<< solve <$> getLine

countLetters :: String -> Char -> Int
countLetters str c = length $ filter (== c) str

solve :: String -> String
solve str | a > d     = "Anton"
          | a < d     = "Danik"
          | otherwise = "Friendship"
  where
    a = countLetters str 'A'
    d = length str - a

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

module Main(main) where

solve a d = case compare a d of
  GT -> "Anton"
  EQ -> "Friendship"
  LT -> "Danik"

main :: IO()
main = do
  c <- getLine
  s <- getLine
  let (a, d) = foldl (\(a, d) l -> if l == 'A' then (a+1, d) else (a, d+1)) (0, 0) s
  putStrLn $ solve a d

countLetters :: String -> Char -> Int
countLetters str c = length $ filter (== c) str

solve :: String -> String
solve str = case compare (countLetters str 'A') (countLetters str 'D') of
    GT -> "Anton"
    EQ -> "Friendship"
    LT -> "Danik"

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

module Main(main) where

t x y = case compare x y of
  GT -> "Anton"
  EQ -> "Friendship"
  LT -> "Danik"

main :: IO()
main = do
  c <- getLine
  s <- getLine
  let (x, y) = foldl (\(x, y) l -> if l == 'A' then (x+1, y)
      else (x, y+1)) (0, 0) s
  putStrLn (t x y)

winner :: Int -> String
winner a
    | a > 0 = "Anton"
    | a < 0 = "Danik"
    | otherwise = "Friendship"

process :: [Char] -> String
process source =
    let count = sum $ map(\x -> if x == 'A' then 1 else -1) source
    in winner count

main :: IO()
main = do
    number <- getLine
    source <- getLine
    let result = process source
    putStrLn result

import Data.List
import Data.Maybe
import Data.Char
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.concat. tail. take 2 . lines
solve :: String->String
solve xs | an>da ="Anton"
         | an<da ="Danik"
         | an==da ="Friendship"
  where [an,da] = foldr (\ a [b1,b2] -> if a=='A' then [b1+1,b2] else [b1,b2+1]) [0,0] xs

import Data.List

main :: IO ()
main = interact $ decide . head . tail .words

decide :: String -> String
decide s
    | aw > dw = "Anton"
    | aw < dw = "Danik"
    | otherwise = "Friendship"
        where (a, d) = partition (=='A') s
              aw = length a
              dw = length d

solve s | a > d     = "Anton"
        | a < d     = "Danik"
        | otherwise = "Friendship"
        where
            a = length $ filter (=='A') s
            d = length $ filter (=='D') s

main = do
    n <- readLn :: IO Int
    s <- getLine
    putStrLn $ solve s

{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}
module Main
( main
) where

import           Prelude hiding (interact, lines, unlines, words, unwords,
                                 sequence, foldr)
import           Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,
                                        unlines, unwords, interact, readInt,
                                        readInteger)
import qualified Data.ByteString.Char8 as BS
import           Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)
import qualified Data.List as L
import qualified Data.IntSet as IS
import           Data.IntSet (IntSet)
import qualified Data.IntMap.Strict as IM
import           Data.IntMap.Strict (IntMap)
import qualified Data.Map.Strict as M
import           Data.Map.Strict (Map)
import qualified Data.Set as S
import           Data.Set (Set)
import qualified Data.Array.IArray as A
import           Data.Array.IArray ((!), Array, listArray, array)
import           Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,
                             catMaybes)
import           Data.Either (either)
import           Control.Applicative (Applicative, pure,
                                      (<$>), (<*>), liftA2, liftA3)
import           Control.Monad (unless, when, void, filterM, ap)
import           Control.Arrow ((***), (&&&), first, second)
import           Data.Traversable (sequence, sequenceA, traverse,
                                   Traversable)
import           Data.Ord (comparing, Down(..))
import           Data.Function (on)
import           Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,
                            bit, shiftR, shiftL, Bits)
import qualified Data.Bits as B
import           Data.Word (Word32)
import           Control.Monad.State (State, get, put, gets, modify,
                                      evalState, execState, runState)
import           Data.Tuple (swap)
import           Data.Foldable (Foldable, foldr)
import           Data.Monoid ((<>), Monoid, mappend, mempty)

type N = Integer
toNum = toInte

answer :: String -> String
answer xs = case go xs of
           (x, y) | x > y -> "Anton"
                  | x < y -> "Danik"
                  | otherwise -> "Friendship"
  where go = foldl' doOne (0,0)
        doOne (x, y) c
          | c == 'A' = let x' = x + 1 in x' `seq` (x',y)
          | otherwise = let y' = y + 1 in y' `seq` (x, y')

handleInput :: ByteString -> ByteString
handleInput = lines
            & coerceInput answer
            & pack
            -- & map (show & pack) & unlines

toInt = readInt & fromJust & fst
toInte = readInteger & fromJust & fst
toX :: Read a => ByteString -> a
toX = unpack & read

coerceInput f (a:b:xs) = f (take (toInt a) (unpack b))
coerceInput _ _ = error "invalid input"

main :: IO ()
main = interact handleInput

-- Util stuff --
(&) :: (a -> b) -> (b -> c) -> a -> c
(&) = flip (.)
infixl 9 &

import Prelude
import Data.Char
import Data.List
import Data.List.Split
import Control.Monad

--
-- {-
-- 96A Football
-- =================================
-- -}
-- isPrefixOf' [] _ = True
-- isPrefixOf' _ [] = False
-- isPrefixOf' (x:xs) (y:ys) = x == y && isPrefixOf' xs ys
--
--  --any'' p = or . map p
--
--  --any' _ [] = False
--  --any' p (x:xs) = p x || any' p xs
--
-- --tails' :: [a] -> [[a]]
-- --tails' [] = []
-- --tails' (x:xs) = (x:xs) : tails' xs
--
-- --isInfixOf' :: Eq a => [a] -> [a] -> Bool
-- --isInfixOf' xs ys = any' (isPrefixOf xs) (tails' ys)
--
-- --football xs
-- --     | isInfixOf' "0000000" xs || isInfixOf' "1111111" xs = "YES"
-- --     | otherwise                                          = "NO"
--
--
-- {-
-- 208A Dubstep
-- =================================
-- -}
-- -- replace = map (\c -> if c == "" then " " else c)
-- -- replace1 = map (\c -> if c == "WUB" then " " else c)
-- -- removeSpaces [] = []
-- -- removeSpaces (x:xs)
-- --     | x == " " = removeSpaces xs
-- --     | otherwise = x:xs
--
-- {-
-- 59A Word
-- =================================
-- -}
--
-- countU [] = 0
-- countU (x:xs)
--     | isUpper x == True = countU xs + 1
--     | otherwise         = countU xs
--
-- countL [] = 0
-- countL (x:xs)
--     | isLower x == True = countL xs + 1
--     | otherwise         = countL xs
--
-- word xs
--     | countL xs >= countU xs = map (toLower) xs
--     | otherwise              = map (toUpper) xs
--

pangram xs
     | (==26) (length (nub  (map (toLower) xs))) = "YES"
     | otherwise                             = "NO"

countA :: String -> Int
countA [] = 0
countA (x:xs)
     | x == 'A'  = countA xs + 1
     | otherwise = countA xs

countD :: String -> Int
countD [] = 0
countD (x:xs)
      | x == 'D'  = countD xs + 1
      | otherwise = countD xs

antonAndDanik xs
    | countA xs > countD xs = "Anton"
    | countA xs < countD xs = "Danik"
    | otherwise             = "Friendship"

main = interact$antonAndDanik

import Control.Applicative

solve :: String -> String
solve a
    | as < bs = "Danik"
    | bs < as = "Anton"
    | otherwise = "Friendship"
    where f l = length $ filter (==l) a
          as = f 'A'
          bs = f 'D'

main = do
    getLine
    l <- getLine
    putStrLn $ solve l

{-#LANGUAGE OverloadedStrings#-}
module Main where

import Data.Text (pack, unpack, splitOn)

main :: IO ()
main = do
    [n] <- getInt
    str <- getLine
    putStrLn (solve n str)

getInt :: IO [Int]
getInt = fmap (map (read . unpack)
            . splitOn " " . pack) getLine

solve :: Int -> String -> String
solve tot str
    | tot < a * 2 = "Anton"
    | tot > a * 2 = "Danik"
    | otherwise = "Friendship"
    where
        a :: Int
        a = foldr (\c ac ->
                    if c == 'A' then ac + 1
                     else ac) 0 str

import Control.Monad

main = readInput >>= putStrLn . decide

anton = "Anton"
danik = "Danik"
tie = "Friendship"

readInput :: IO (Int, String)
readInput = liftM2 toTuple getLine getLine
  where toTuple a b = (read a, b)

decide :: (Int, String) -> String
decide (n, winners) = decide' winners 0 0
  where decide' [] a d
          | a == d = tie
          | a < d = danik
          | otherwise = anton
        decide' (x:xs) a d
          | half < a = anton
          | half < d = danik
          | otherwise = case x of
                          'A' -> decide' xs (a + 1) d
                          _   -> decide' xs a (d + 1)
        half = div n 2

import Text.Printf
import Data.List
import Data.Functor
import Control.Applicative
import Prelude
import Control.Monad
import Data.Maybe
import Data.Function

readInt :: String -> Int
readInt = Prelude.read

solve :: Int -> Int -> String
solve countA countD
    | countA > countD = "Anton"
    | countA < countD = "Danik"
    | otherwise       = "Friendship"

main :: IO ()
main = do
    getLine
    history <- getLine
    let countA = length . filter (== 'A') $ history
        countD = length . filter (== 'D') $ history
    printf "%s" $ solve countA countD

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import System.IO
import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.ST.Safe as SA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

getWords  = words <$> getLine :: IO [String]
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]
getDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()

---- Answer Code Section ----

process :: String -> Int -> String
process plays n = let anton = length $ filter (== 'A') plays in
    case compare anton (n - anton) of
        LT -> "Danik"
        EQ -> "Friendship"
        GT -> "Anton"

main = do
    n <- getInt
    plays <- getLine
    putStrLn $ process plays n

import Control.Monad
import Data.Array
import Data.Char
import Data.Functor
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import qualified Data.ByteString.Char8 as B

solve :: (Ord a) => a -> a -> String
solve x y
    | x > y = "Anton"
    | x < y = "Danik"
    | x == y = "Friendship"

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

main :: IO ()
main = do
    n <- getLine
    s <- getLine
    let countA = count 'A' s
        countD = count 'D' s
    print $ solve countA countD

import System.IO

solve :: String -> String
solve s =
  let a = length $ filter (=='A') s
      d = length $ filter (=='D') s
  in case a `compare` d of
       LT -> "Anton"
       EQ -> "Friendship"
       GT -> "Danik"

main = do
  getLine
  putStrLn =<< solve <$> getLine

import Control.Applicative

solve :: String -> String
solve a
    | as < bs = "Danik"
    | bs < as = "Anton"
    | otherwise = "Friendship"
    where f l = length $ filter (==l) a
          as = f 'A'
          bs = f 'B'

main = do
    getLine
    l <- getLine
    putStrLn $ solve l

import Control.Applicative
import Data.List

main=do
    n<- read <$> getLine ::IO Int
    a<-   getLine
    let b = length $ filter (=='A') a
    putStrLn $ if b > n-b then "Anton" else "Danik"

import System.Environment
import Control.Monad

main :: IO ()
main = do
  [_, s] <- replicateM 2 getLine
  let as = length $ filter (=='A') s
  let ds = length $ filter (=='D') s
  if as > ds then print "Anton"
    else if as < ds then print "Danik"
    else print "Friendship"

module Main where

main :: IO ()
main = interact $ f . (\(_:x:_) -> x) . words

f :: String -> String
f xs | length (filter (=='D') xs) *2 > length xs = "Danik"
     | length (filter (=='D') xs) *2 < length xs = "Anton"
     | otherwise = "Frendship"


{-# LANGUAGE BangPatterns #-}

import Control.Monad ( replicateM, replicateM_ )
import Data.List ( sort, foldl' ) --'
import Data.Array
import Data.Int (Int64)

type Graph = Array Int [Int]

subtreeSizes :: Graph -> Int -> (Int, [Int]) -> Int -> (Int, [Int])
subtreeSizes g !par (!tot, ss) !v = let
  children = filter (/= par) (g ! v)
  (ownSize, res) = foldl' {-'-} (subtreeSizes g v) (1, ss) children
  in  (tot + ownSize, ownSize : res)

eVal :: Int -> Int -> Int64
eVal totSize subSize = let
  ts = fromIntegral totSize
  ss = fromIntegral subSize
  in  (ts - ss) * ss

modVal :: Int64
modVal = 10^(9::Int) + 7;

trim :: Int -> [Int64] -> [Int64]
trim k li = case  li  of
  v1 : v2 : xs  | k > 0  ->
    let
      nv = rem (v1*v2) modVal
    in  seq nv $ trim (k-1) (nv : xs)
  _  -> li

reduce :: [(Int64, Int64)] -> Int64
reduce = foldl' step 0  where --'
  step s (x,y) = rem (s + x*y) modVal

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- read <$> getLine
    edges <- replicateM (n-1) $ do
      [u, v] <- map read . words <$> getLine
      pure [(u, v), (v,u)]
    let
      g = accumArray (flip (:)) [] (1, n) $ concat edges
      (ec, subSizes) = foldl' {-'-} (subtreeSizes g 1) (1, []) (g ! 1)
      eVals = reverse . sort $ map (eVal n) subSizes
    if  ec /= n  then  putStrLn "yikes"  else  pure ()
    m <- read <$> getLine
    factors <- map read . words <$> getLine :: IO [Int64]
    let  labels = trim (m - (n-1)) (reverse $ sort factors) ++ repeat 1
    --putStrLn "labels, eVals:"
    --print $ zip labels eVals
    --putStrLn "answer:"
    print $ reduce (zip eVals labels)

{-# LANGUAGE BangPatterns #-}

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

type Graph = Array Int [Int]

subtreeSizes :: Graph -> Int -> (Int, [Int]) -> Int -> (Int, [Int])
subtreeSizes g !par (!tot, ss) !v = let
  children = filter (/= par) (g ! v)
  (ownSize, res) = foldl' (subtreeSizes g v) (1, ss) children
  in  (tot + ownSize, ownSize : res)

eVal :: Int -> Int -> Int64
eVal totSize subSize = let
  ts = fromIntegral totSize
  ss = fromIntegral subSize
  in  (ts - ss) * ss

modVal :: Int64
modVal = 10^(9::Int) + 7;

trim :: Int -> [Int64] -> [Int64]
trim k li = case  li  of
  v1 : v2 : xs  | k > 0  ->
    let
      nv = rem (v1*v2) modVal
    in  seq nv $ trim (k-1) (nv : xs)
  _  -> li

reduce :: [(Int64, Int64)] -> Int64
reduce = foldl' step 0  where
  step s (x,y) = rem (s + x*y) modVal

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

test :: IO ()
test = do
  n <- read <$> getLine
  edges <- replicateM (n-1) $ do
    [u, v] <- map read . words <$> getLine
    pure [(u, v), (v,u)]
  m <- read <$> getLine
  factors <- map read . words <$> getLine :: IO [Int64]
  let
    g = accumArray (flip (:)) [] (1, n) $ concat edges
    (_, subSizes) = foldl' (subtreeSizes g 1) (1, []) (g ! 1)
    eVals = reverse . sort $ map (eVal n) subSizes
    labels = trim (m - (n-1)) (reverse $ sort factors) ++ repeat 1
  print $ reduce (zip eVals labels)


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

getA = fmap (map read . words) getLine

gao [] = [0]
gao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where
	s = gao r
	d = scanl (+) (0::Int64) $ map (subtract x . head) r

main = do
	[n] <- getA
	a <- replicateM (fromIntegral n) getA
	putStrLn $ show $ head $ gao $ sort a

import Data.Int (Int64)

bestpin [] _ _ = 1000000000000000::Int64
bestpin ((dpr,dpwp,dpx):dptail) sx nx = min (sx - nx * dpx + dpwp) (bestpin dptail (sx + dpx) (nx + 1))

solve [] [] = 0
solve [] ((c,x):cxtail) = solve [(c,c,x)] cxtail
solve ((dpr,dpwp,dpx):dptail) [] = dpr

solve ((dpr,dpwp,dpx):dptail) ((c,x):cxtail) =
  let score_withpin = dpr + c
      score_nopin = bestpin ((dpr,dpwp,dpx):dptail) x 1
  in solve (((min score_withpin score_nopin),score_withpin,x):((dpr,dpwp,dpx):dptail)) cxtail

mergetwo [] ys = ys
mergetwo xs [] = xs
mergetwo ((cx,xx):xs) ((cy,xy):ys) = if xx <= xy then
  ((cx,xx):(mergetwo xs ((cy,xy):ys))) else
  ((cy,xy):(mergetwo ((cx,xx):xs) ys))

mergesort [] = []
mergesort [t] = [t]
mergesort cxs =
  let n = length cxs
      n2 = n `div` 2
      leftSide = take n2 cxs
      rightSide = drop n2 cxs
  in mergetwo (mergesort leftSide) (mergesort rightSide)

readNPairs 0 = return []
readNPairs n = do
  [x,c] <- fmap ( (map (\x -> read x::Int64)) . words ) getLine
  rest <- readNPairs (n - 1)
  return ((c,x):rest)

main = do
  n <- readLn::IO Int
  v <- readNPairs n
  print $ solve [] (mergesort v)

import Control.Monad
import Data.List

getA = fmap (map read . words) getLine

gao [] = [0]
gao ([x,c]:r) = c + minimum (zipWith (+) d s) : s where
	s = gao r
	d = scanl (+) 0 $ map (subtract x . head) r

main = do
	[n] <- getA
	a <- replicateM n getA
	putStrLn $ show $ head $ gao $ sort a

bestpin [] _ _ = 1000000000::Int
bestpin ((dpr,dpwp,dpx):dptail) sx nx = min (sx - nx * dpx + dpwp) (bestpin dptail (sx + dpx) (nx + 1))

solve [] [] = 0
solve [] ((c,x):cxtail) = solve [(c,c,x)] cxtail
solve ((dpr,dpwp,dpx):dptail) [] = dpr

solve ((dpr,dpwp,dpx):dptail) ((c,x):cxtail) =
  let score_withpin = dpr + c
      score_nopin = bestpin ((dpr,dpwp,dpx):dptail) x 1
  in solve (((min score_withpin score_nopin),score_withpin,x):((dpr,dpwp,dpx):dptail)) cxtail

mergetwo [] ys = ys
mergetwo xs [] = xs
mergetwo ((cx,xx):xs) ((cy,xy):ys) = if xx <= xy then
  ((cx,xx):(mergetwo xs ((cy,xy):ys))) else
  ((cy,xy):(mergetwo ((cx,xx):xs) ys))

mergesort [] = []
mergesort [t] = [t]
mergesort cxs =
  let n = length cxs
      n2 = n `div` 2
      leftSide = take n2 cxs
      rightSide = drop n2 cxs
  in mergetwo (mergesort leftSide) (mergesort rightSide)

readNPairs 0 = return []
readNPairs n = do
  [x,c] <- fmap ( (map (\x -> read x::Int)) . words ) getLine
  rest <- readNPairs (n - 1)
  return ((c,x):rest)

main = do
  n <- readLn::IO Int
  v <- readNPairs n
  print $ solve [] (mergesort v)

bestpin [] _ _ = 1000000000000000::Int
bestpin ((dpr,dpwp,dpx):dptail) sx nx = min (sx - nx * dpx + dpwp) (bestpin dptail (sx + dpx) (nx + 1))

solve [] [] = 0
solve [] ((c,x):cxtail) = solve [(c,c,x)] cxtail
solve ((dpr,dpwp,dpx):dptail) [] = dpr

solve ((dpr,dpwp,dpx):dptail) ((c,x):cxtail) =
  let score_withpin = dpr + c
      score_nopin = bestpin ((dpr,dpwp,dpx):dptail) x 1
  in solve (((min score_withpin score_nopin),score_withpin,x):((dpr,dpwp,dpx):dptail)) cxtail

mergetwo [] ys = ys
mergetwo xs [] = xs
mergetwo ((cx,xx):xs) ((cy,xy):ys) = if xx <= xy then
  ((cx,xx):(mergetwo xs ((cy,xy):ys))) else
  ((cy,xy):(mergetwo ((cx,xx):xs) ys))

mergesort [] = []
mergesort [t] = [t]
mergesort cxs =
  let n = length cxs
      n2 = n `div` 2
      leftSide = take n2 cxs
      rightSide = drop n2 cxs
  in mergetwo (mergesort leftSide) (mergesort rightSide)

readNPairs 0 = return []
readNPairs n = do
  [x,c] <- fmap ( (map (\x -> read x::Int)) . words ) getLine
  rest <- readNPairs (n - 1)
  return ((c,x):rest)

main = do
  n <- readLn::IO Int
  v <- readNPairs n
  print $ solve [] (mergesort v)


import Control.Applicative

main = do
    (n:k:_) <- (return.map read.words =<< getLine :: IO [Int])
    pairs <- gets n
    putStrLn.show $ answer k $ foldl add 0 pairs

add :: Int -> (Int,Int) -> Int
add v (l,r) = v+r-l+1

answer :: Int -> Int -> Int
answer k x
    | x `mod` k == 0 = 0
    | k > x = k - x
    | k < x = k - (mod x k)

gets :: Int -> IO [(Int,Int)]
gets 0 = return []
gets n = do
    (l:r:_) <- (return.map read.words =<< getLine :: IO [Int])
    ((l,r):) <$> gets (n-1)

import Control.Monad
import Control.Applicative

main = do
    [n,k] <- map read . words <$> getLine
    l <-replicateM n ((\[x,y] -> y-x+1) . map read . words <$> getLine)
    let x = sum l `mod`k
    print $ if x == 0 then 0 else k - x

import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Maybe

main = do
    [n,k] <- map (fromMaybe 0. fmap fst . B.readInt) . B.words <$> B.getLine
    l <-replicateM n ((\[x,y] -> y-x+1) . map (fromMaybe 0 . fmap fst . B.readInt) . B.words <$> B.getLine)
    let x = sum l `mod`k
    print $ if x == 0 then 0 else k - x

import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B

main = B.interact $ showBI . rd . B.lines

rd (nk:qs) = go (readBI . last . B.words $ nk) (map (map readBI . B.words) qs)
go :: Int -> [[Int]] -> Int
go k qs = (\x -> if x==k then 0 else x) . (`subtract`k) . (`mod`k) . sum $ map (\(l:r:[]) -> r-l+1) qs

showBI :: Int -> B.ByteString
showBI = B.pack . show

readBI :: B.ByteString -> Int
readBI = fst . fromJust . B.readInt

import Control.Monad (liftM, replicateM)
import Data.Array (Array, (!), array, bounds)
import Data.Char (ord)
import Data.List (intercalate)

solve :: Int -> [[Int]] -> Int
solve k as  =  (k - s `mod` k) `mod` k
  where
    s  =  sum [r - l + 1 | [l, r] <- as]

main :: IO ()
main  =  do
    [n, k]  <-  reads
    as  <-  replicateM n reads
    print $ solve k as
  where

    reads :: Num a => IO [a]
    reads  =  liftM (map read . words) getLine
      where
        read ('-':s)  =  (-1) * read s
        read s  =  read' 0 s
        read' a ""  =  a
        read' a (c:s)  =  read' (10 * a + fromIntegral (ord c - ord '0')) s

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

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

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 readInt.B.words <$> B.getContents
  print $ solve k xs

solve k xs = go 0 xs
   where
     go !acc (l:r:rest) = go (acc+r-l+1) rest
     go acc _ = if r==0 then 0 else k-r
      where
        r = acc`mod`k

import Control.Applicative

main = do
    (n:k:_) <- (return.map read.words =<< getLine :: IO [Int])
    pairs <- gets n
    putStrLn.show $ answer k $ foldl add 0 pairs

add :: Int -> (Int,Int) -> Int
add v (l,r) = v+r-l+1

answer :: Int -> Int -> Int
answer k x
    | k `mod` x == 0 = 0
    | k > x = k - x
    | k < x = k - (mod x k)

gets :: Int -> IO [(Int,Int)]
gets 0 = return []
gets n = do
    (l:r:_) <- (return.map read.words =<< getLine :: IO [Int])
    ((l,r):) <$> gets (n-1)

import Control.Applicative

main = do
    (n:k:_) <- (return.map read.words =<< getLine :: IO [Int])
    pairs <- gets n
    putStrLn.show $ answer k $ foldl add 0 pairs

add :: Int -> (Int,Int) -> Int
add v (l,r) = v+r-l+1

answer :: Int -> Int -> Int
answer k x
    | k == x = 0
    | k > x = k - x
    | k < x = k - (mod x k)

gets :: Int -> IO [(Int,Int)]
gets 0 = return []
gets n = do
    (l:r:_) <- (return.map read.words =<< getLine :: IO [Int])
    ((l,r):) <$> gets (n-1)


import Data.List
import Control.Applicative

solve :: [Int] -> [Int] -> [Int]
solve _ [] = []
solve ls (a:as) = (ls !! aa) : (solve ((drop (aa+1) ls) ++ (take aa ls)) as)
    where
        aa = mod a $ length ls

main = do
    [n,k] <- map read <$> words <$> getLine
    a <- map read <$> words <$> getLine
    putStrLn $ concat $ intersperse " " $ map show $ solve [1..n] a

main :: IO ()
main = interact mf

mf :: String -> String
mf t =
  let [[n, _], b] = map (map read . words) $ lines t
  in unwords $ map show $ step 1 n [1..n] b

delAt :: [a] -> Int -> [a]
delAt s i =
  let (ys,zs) = splitAt i s
  in ys ++ tail zs

step ::Int -> Int -> [Int] -> [Int] -> [Int]
step _ _ _ [] = []
step i n cs (a:as)
  |i > n = step (i - n) n cs (a:as)
  |(a + i) `mod` n == 0 =
    last cs : step 1 (n-1) (init cs) as
  |otherwise =
    let ri = (a + i) `mod` n
        el = cs !! (ri - 1)
    in el : step ri (n-1) (delAt cs (ri-1)) as

main :: IO ()
main = do
  fl <- getLine
  sl <- getLine
  let [n, _] = map read $ words fl
  let b = map read $ words sl
  putStrLn $ unwords $ map show $ step 1 n [1..n] b

mf :: String -> String
mf t =
  let [x, y] = map words $ lines t
      [n, _] = map read x
      b = map read y
  in unwords $ map show $ step 1 n [1..n] b

delAt :: [a] -> Int -> [a]
delAt s i =
  let (ys,zs) = splitAt i s
  in ys ++ tail zs

step ::Int -> Int -> [Int] -> [Int] -> [Int]
step _ _ _ [] = []
step i n cs (a:as)
  |i > n = step (i - n) n cs (a:as)
  |(a + i) `mod` n == 0 =
    last cs : step 1 (n-1) (init cs) as
  |otherwise =
    let ri = (a + i) `mod` n
        el = cs !! (ri - 1)
    in el : step ri (n-1) (delAt cs (ri-1)) as
step i n cs as = error $ show (i,n, cs, as)

import Data.List

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

solve :: [Int] -> [Int]
solve (n:_:a) = solve' n [1..n] a

solve' :: Int -> [Int] -> [Int] -> [Int]
solve' _ _ [] = []
solve' n q (a:ax) = let (rear, front) = splitAt (a `mod` n) q
                    in  if null front
                        then head rear : solve' (n - 1) (tail rear) ax
                        else head front : solve' (n - 1) (tail front ++ rear) ax

{-# OPTIONS_GHC -fno-warn-tabs #-}
import Data.List;
import System.IO;
import Data.Maybe;

printOrder :: [Int] -> IO ();
printOrder n = do
	print(head n);
	if(length (tail n) > 0) then printOrder(tail n) else return();

childOut :: Int -> Int -> Int -> [Int] -> [Int] -> [Int] -> [Int];
childOut i n curCh ch stps fin
	| i == n = fin
	| otherwise = childOut (i+1) n (if chosen == (length usingNextCh) then 0 else chosen) usingNextCh stps ((ch!!chosen):fin) where
		chosen = if((curCh + stps!!i) >= length ch) then (curCh + stps!!i) `mod` (length ch) else (curCh + stps!!i)
		usingNextCh = take chosen ch ++ drop (chosen + 1) ch;

main = do
	str0 <- getLine;
	str1 <- getLine;
	let ns0 = map (read :: String -> Int) (words str0);
	let childn = [1..ns0!!0];
	let stepsCount = ns0!!1;
	let steps = map (read :: String -> Int) (words str1);
	let childOutOrder = childOut 0 stepsCount 0 childn steps [];
	printOrder(reverse childOutOrder);

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

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

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

solve :: [Int] -> [Int]
solve (n : _ : xs) = solve' n xs [1..n]

solve' :: Int -> [Int] -> [Int] -> [Int]
solve' _ [] _ = []
solve' n (x:xs) k =
    let (mae, ushiro) = splitAt (x `mod` n) k
    in  if null ushiro
        then head mae : solve' (n - 1) xs (tail mae)
        else head ushiro : solve' (n - 1) xs (tail ushiro ++ mae)

main = do
    (map nextInt . C.words -> xs) <- B.getContents
    putStrLn $ unwords $ map show (solve xs)

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

import Control.Monad (forM_, forM)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe (fromJust)
import Data.List (intercalate, delete)

readint = fst. fromJust . C.readInt

run gs (x:xs) i = (gs !! y):run gs' xs y
    where y = (x + i) `mod` (length gs)
          gs' = delete (gs !! y) gs
run _ [] _ = []

main = do
    (map readint . C.words -> [n, k]) <- B.getLine
    (map readint . C.words -> xs) <- B.getLine
    putStrLn $ intercalate " " $ map show (run [1..n] xs 0)

import Data.List
import Control.Applicative

solve :: [Int] -> [Int] -> [Int]
solve _ [] = []
solve ls (a:as) = (ls !! aa) : (solve ((drop (aa+1) ls) ++ (take aa ls)) as)
    where
        aa = mod a $ length ls

main = do
    [n,k] <- map read <$> words <$> getLine
    a <- map read <$> words <$> getLine
    putStrLn $ intersperse ' ' $ concat $ map show $ solve [1..n] a


import Data.Functor

main = do
    [_,_,k] <- map (pred.read).words <$> getLine
    p <- getLine
    op <- getLine

    let (a,b) = foldl solve (reverse $ take k p, drop k p) op
    putStrLn $ reverse a ++ b

solve (x:l,r) 'L' = (l, x:r)
solve (l,x:r) 'R' = (x:l, r)
solve (l,'(':r) 'D' = bounds (l, rm r 1)
solve (l,')':r) 'D' = bounds (rm l (0-1), r)
bounds (x:l,[]) = (l,[x])
bounds a = a

rm s 0 = s
rm (')':s) b = rm s (b - 1)
rm ('(':s) b = rm s (b + 1)

import Data.List
import Data.Functor

main :: IO()
main = do
    [_, _, k] <- map read . words <$> getLine
    brackets <- getLine
    operations <- getLine
    let (left, right) = splitAt (k - 1) brackets
        (remLeft, remRight) = foldl solve (reverse left, right) operations
    putStrLn $ reverse remLeft ++ remRight

solve :: (String, String) -> Char -> (String, String)
solve (l:lx, r) 'L' = (lx, l:r)
solve (l, r:rx) 'R' = (r:l, rx)
solve (l, '(':rx) 'D' = recover (l, remove rx 1)
solve (l, ')':rx) 'D' = recover (remove l (-1), rx)

remove :: String -> Int -> String
remove s 0 = s
remove ('(':sx) sum = remove sx (sum + 1)
remove (')':sx) sum = remove sx (sum - 1)

recover :: (String, String) -> (String, String)
recover (l:lx, []) = (lx, [l])
recover x = x


solve ["front", "1"] = "L"
solve ["front", "2"] = "R"
solve ["back",  "1"] = "R"
solve ["back",  "2"] = "L"

main = do text <- readFile "input.txt"
          writeFile "output.txt" (solve $ words text)

import System.IO

main = do
	hin<-openFile "input.txt" ReadMode
	hout<-openFile "output.txt" WriteMode
	door<-hGetLine hin
	handrail<-hGetLine hin
	hPutStrLn hout (solve door (read handrail))
	hClose hout
	hClose hin

solve "front" 1 = "L"
solve "back" 2 = "L"
solve "front" 2 = "R"
solve "back" 1 = "R"

main = readFile "input.txt" >>= writeFile "output.txt" . (\[d, r] -> if d == r then "L\n" else "R\n") . map ((=="1") . f) . lines
	where f "front" = "1"; f x = x

solve ["front","1"] = "L"
solve ["front","2"] = "R"
solve ["back", "1"] = "R"
solve ["back", "2"] = "L"

main = readFile "input.txt" >>= writeFile "output.txt" . solve . words

#! /usr/bin/runhaskell
main = do
  file <- readFile "input.txt"
  writeFile "output.txt" (f file)

f file =
  if (hstr == "front" && lstr == "1") || (hstr == "back" && lstr == "2")
     then "L\n"
  else "R\n"
    where str = words file
          hstr = head str
          lstr = last str

import IO

solve :: String -> Int -> String
solve "front" 1  =  "L"
solve "front" 2  =  "R"
solve "back"  1  =  "R"
solve "back"  2  =  "L"
solve _ _ = error "..."

main :: IO ()
main  =  do
    hInput  <-  openFile "input.txt" ReadMode
    hOutput  <-  openFile "output.txt" WriteMode

    d <- hGetLine hInput
    n <- hGetLine hInput >>= return . read
    hPutStrLn hOutput (solve d n)

    hClose hOutput
    hClose hInput

import System.IO

main = do
	hin<-openFile "input.txt" ReadMode
	hout<-openFile "output.txt" WriteMode
	door<-hGetLine hin
	handrail<-hGetLine hin
	hPutStrLn hout (solve door (read handrail))

solve "front" 1 = "L"
solve "back" 2 = "L"
solve "front" 2 = "R"
solve "back" 1 = "R"


{-# LANGUAGE CPP, BlockArguments, DatatypeContexts, DeriveFunctor, GADTs, LambdaCase, NumericUnderscores, OverloadedStrings, ScopedTypeVariables, TupleSections  #-}
{-# LANGUAGE Strict #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}
#ifndef DEBUG
{-# LANGUAGE Safe #-}
#endif

import qualified Data.ByteString.Char8 as B8
import qualified Data.String as S
import qualified Data.Text as T

import Control.Arrow ((>>>))
import Data.Functor ((<&>))
import Data.Maybe

import qualified Control.Monad as M

import Data.Char

import Text.Printf

#ifdef DEBUG
import Debug.Trace (trace, traceM, traceShowM)
debug = flip trace

tracing t x = trace (t ++ " = " ++ show x) x
debugging x t = tracing t x

#else

debug x _ = x
trace _ x = x
tracing _ x = x
debugging x _ = x

traceM _ = pure
#endif

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

{- writing -}
putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- solution -}

solve :: Int -> String -> String
solve n str = reverse . solve' n $ reverse str
    where
        solve' :: Int -> String -> String
        solve' n str@('0':c1:c0:otherStr) | n >= 3 = decodeChars [c0, c1] : solve' (n - 3) otherStr
        solve' n str@(c:otherStr) = decodeChars [c] : solve' (n - 1) otherStr
        solve' 0 _ = []

        decodeChars :: String -> Char
        decodeChars [c] = chr $ decodeChar c + ord 'a' - 1
        decodeChars [c1, c0] = chr (10 * decodeChar c1 + decodeChar c0 + ord 'a' - 1)
        decodeChars _ = error ""

        decodeChar :: Char -> Int
        decodeChar c = ord c - ord '0'

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    M.replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        str <- B8.getLine <&> B8.unpack <&> (T.unpack . T.strip . T.pack)
        let answer = solve n str
        B8.putStrLn $ B8.pack answer

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

{-# LANGUAGE Safe                #-}
{-# LANGUAGE ImportQualifiedPost #-}

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

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

import Prelude               hiding (getLine)
import System.IO                    (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

readI s | isOk       = read s :: Int
        | otherwise  = 1  -- debug
  where
    isOk = (== length s) . length . filter (<='9') . filter (>='0') $ s

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        _n <- getLine
        take 50 . filter (<='9') . filter (>='0') <$> getLine
    mapM_ (putStrLn.solve) tcs

solve s = map toC . L.reverse . f . L.reverse $ s
  where
    f []           = []
    f ('0':a:b:cs) = readI [b,a] : f cs
    f (      b:cs) = readI [b  ] : f cs

    toC n | (1 <= n && n <= 26)  = chr (ord 'a' + (n-1))
          | otherwise            = 'a'  -- debug

import Control.Monad (replicateM_)
import Data.Char (ord, chr)

main = read <$> getLine >>= flip replicateM_ scase
scase = getLine >> getLine >>= putStrLn . reverse . decode . reverse

ec :: Int -> Char
ec c = chr ((ord 'a') + c - 1)

c2d :: Char -> Int
c2d c = (ord c) - (ord '0')

decode :: String -> String
decode ('0':b:a:rest) = (ec $ 10*(c2d a)+ (c2d b)) : decode rest
decode (a:rest) = ec (c2d a) : decode rest
decode [] = []

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

{-# LANGUAGE Safe                #-}
{-# LANGUAGE ImportQualifiedPost #-}

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

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

import Prelude               hiding (getLine)
import System.IO                    (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

readI s = read s :: Int

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [_n] <- ri
        getLine
    mapM_ (putStrLn.show.solve) tcs

solve s = L.reverse . f . L.reverse $ s
  where
    f []           = []
    f ('0':a:b:cs) = readI [b,a] : f cs
    f (      b:cs) = readI [b  ] : f cs


pairUp :: [String] -> [(String, String)]
pairUp [] = []
pairUp (x : y : t) = (x, y) : pairUp t

toArr :: (Num a, Read a) => String -> [a]
toArr = map (read :: Read a => String -> a) . words

toSolveInp :: (String, String) -> (Integer, [Integer])
toSolveInp (s, t) = (k, p)
    where p      = toArr t
          [_, k] = toArr s

go :: Integer -> Integer -> [Integer] -> Integer
go k acc [] = 0
go k acc (p : ps) = max 0 (leastAcc - acc) + go k (newAcc + p) ps
  where (d, m) = divMod (100 * p) k
        leastAcc = if m > 0 then d + 1 else d
        newAcc = max acc leastAcc

solve :: Integer -> [Integer] -> Integer
solve k (p : ps) = go k p ps

main :: IO ()
main = interact
  (unlines . map (show . uncurry solve . toSolveInp) . pairUp . tail . lines)

pairUp :: [String] -> [(String, String)]
pairUp [] = []
pairUp (x : y : t) = (x, y) : pairUp t

solve :: Integer -> [Integer] -> Integer
solve k (p : ps) = go p ps
    where go acc [] = 0
          go acc (p : ps) = max 0 (leastAcc - acc) + go (newAcc + p) ps
            where (d, m) = divMod (100 * p) k
                  leastAcc = if m > 0 then d + 1 else d
                  newAcc = max acc leastAcc

-- p / acc <= k / 100
-- 100 * p <= k * acc

main :: IO ()
main = interact (unlines . map (show . uncurry solve . toInp) . pairUp . tail . lines)
    where toArr = map (read :: String -> Integer) . words
          toInp (s, t) = (k, p)
            where p = toArr t
                  [n, k] = toArr s

module Main where

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

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

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

solve :: Int64 -> Int64 -> [Int64] -> Int64
solve k = foldl func
    where func preSum x = preSum+x+needAdd
            where minPS = (100*x+k-1) `div` k
                  needAdd = if minPS > preSum then minPS - preSum else 0

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

module Main where

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

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

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

solve :: Int64 -> [Int64] -> Int64 -> Int64
solve presum [] _ = 0
solve presum (x:xs) k = needAdd + solve (presum+x+needAdd) xs k
    where minPS = (100*x+k-1) `div` k
          needAdd = if minPS > presum then minPS - presum else 0

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

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

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

test :: IO ()
test = do
  [_, k] <- map read . words <$> getLine :: IO [Integer]
  ps <- map read . words <$> getLine :: IO [Integer]
  print $ maximum $ (0 :) $ zipWith (\p a -> (100 * p - 1) `div` k + 1 - a) (tail ps) (scanl1 (+) ps)

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

solve [] _ _ = 0
solve (x:xs) s k = solve xs (s+x+r) k + r
            where
                d = div (100*x+k-1) k
                r = if d <= s then 0 else d - s

printResult = do
    [n,k] <- readInts
    (p:ps) <- readInts
    print $ solve ps p k

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

import Control.Monad
import Data.Maybe
import Data.List
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
    [n, k] <- getInts
    ps <- getInts
    let
      qs = tail $ scanl' (+) (0 :: Integer) (map fromIntegral $ take (length ps - 1) ps)
      check x = all id $ map (\(q, p) -> 100 * p <= fromIntegral k * (q + x)) $ zip qs (map fromIntegral $ tail ps)
      func low high
        | low == high = low
        | check x = func low x
        | otherwise = func (x + 1) high
        where
        x = (low + high) `div` 2
    C.putStrLn $ C.pack $ show $ func 0 ((10 :: Integer) ^ 18)

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

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

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

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

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

solve :: Int -> Int64 -> [Int64] -> Int64
solve n k ps = solve' (head ps) (tail ps)
    where
        solve' :: Int64 -> [Int64] -> Int64
        solve' _ [] = 0
        solve' sumP ps@(p:restPs) = max currentDeltaP $ solve' (sumP + p) restPs
            where
                currentDeltaP = max 0 $ (p * 100 - k * sumP + k - 1) `div` k

                    -- (p * 100 - k * sumP) / k <=deltaP

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

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

import qualified Data.ByteString.Lazy.Char8 as P

import Data.List
import Data.Int

type SIO = StateT P.ByteString IO

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

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

ceilDiv :: Integral t => t -> t -> t
ceilDiv n k = div (n + k - 1) k

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, k] <- readInts
    p <- map fromIntegral <$> readInts
    let
      k' = fromIntegral k :: Int64
      ps = scanl' (+) 0 p
      rates = tail [ceilDiv (v * 100) k' - s | (v, s) <- zip p ps]
      ans = maximum (0:rates)
    lift . print $ ans

pairUp :: [String] -> [(String, String)]
pairUp [] = []
pairUp (x : y : t) = (x, y) : pairUp t

toArr :: (Num a, Read a) => String -> [a]
toArr = map (read :: Read a => String -> a) . words

toSolveInp :: (String, String) -> (Int, [Int])
toSolveInp (s, t) = (k, p)
    where p      = toArr t
          [_, k] = toArr s

go :: Int -> Int -> [Int] -> Int
go k acc [] = 0
go k acc (p : ps) = max 0 (leastAcc - acc) + go k (newAcc + p) ps
  where (d, m) = divMod (100 * p) k
        leastAcc = if m > 0 then d + 1 else d
        newAcc = max acc leastAcc

solve :: Int -> [Int] -> Int
solve k (p : ps) = go k p ps

main :: IO ()
main = interact
  (unlines . map (show . uncurry solve . toSolveInp) . pairUp . tail . lines)

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

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

test :: IO ()
test = do
  [_, k] <- map read . words <$> getLine :: IO [Integer]
  ps <- map read . words <$> getLine :: IO [Integer]
  print $ maximum $ (0 :) $ zipWith (\p a -> 100 * p - a * k) (tail ps) (scanl1 (+) ps)


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

main = getLine >>= flip replicateM_ test . read

test = do
    (n:k:_) <- map read . words <$> getLine
    print $
        minimum
            [ n `div` d
            | d1 <- [1 .. min (ceiling $ sqrt $ fromIntegral n) k]
            , n `mod` d1 == 0
            , d <- [d1, n `div` d1]
            , d <= k
            ]

import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    print $ f n k

f :: Int -> Int -> Int
f n k =
    minimum
        . filter (\x -> div n x <= k)
        . concatMap (\x -> [x, div n x])
        . filter (\x -> mod n x == 0)
        $ takeWhile (\x -> x * x <= n) [1 ..]

import Control.Monad (replicateM_)

getDivisors n limit = [x | x <- [1 .. limit], n `mod` x == 0]

getShovelType :: [Int] -> Int
getShovelType [n, k] =
    if length beforeSqrt == 0 then head afterSqrt
    else head beforeSqrt
    where
        limit = (round . sqrt . fromIntegral) n
        divisors = getDivisors n limit
        beforeSqrt = filter (\x -> n `div` x <= k) divisors
        afterSqrt = filter (\x -> n `div` x <= k) ((reverse . map (\x -> n `div` x)) divisors)

readLine :: IO [Int]
readLine = (map read) . words <$> getLine

main =
    read <$> getLine >>= \t ->
    replicateM_ t (getShovelType <$> readLine >>= print)

import Control.Monad ( replicateM_ )

readInput = (map read . words <$> getLine)

buyingShovels :: [Int] -> Int
buyingShovels [n, k] = head (cands' ++ cands'')
    where upper = ceiling.sqrt.fromIntegral $ n
          cands' = filter (\x -> n`mod`x==0 && n`div`x<=k) [1..upper]
          cands'' = [n`div`x | x<-[upper,upper-1..1], n`mod`x==0, x<=k]

main = do
    t <- read <$> getLine
    replicateM_ t (buyingShovels <$> readInput >>= print)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/D

import Control.Monad ( replicateM_ )

buyingShovels :: [Int] -> Int
buyingShovels [n, k] = head (cands1 ++ cands2) where
    upper = ceiling . sqrt . fromIntegral $ n
    increasing = [1 .. upper]
    decreasing = [upper, upper-1 .. 1]
    cands1 = [x | x <- increasing, n `div` x <= k, n `mod` x == 0]
    cands2 = [n `div` x | x <- decreasing, x <= k, n `mod` x == 0]

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

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (buyingShovels <$> readInput >>= print)

parse :: String -> [(Int, Int)]
parse inp = [(n, k) | [n, k] <- map (map read . words) . tail $ lines inp]

factors :: Int -> [Int]
factors n = sf ++ reverse (map (quot n) sf)  where
  sf = [w | w <- takeWhile (\w -> w*w <= n) [1..], rem n w == 0]

solve :: (Int, Int) -> Int
solve (n, k) = (quot n) . last . filter (<= k) $ factors n

showAns :: [Int] -> String
showAns = unlines . map show

main :: IO ()
main = interact (showAns . map solve . parse)

import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    print $ f n k

f :: Int -> Int -> Int
f n k | null pds  = n
      | otherwise = minimum pds
  where
    pds =
        filter (\x -> x * k >= n)
            . concatMap (\x -> [x, div n x])
            . filter (\x -> mod n x == 0)
            . takeWhile (\x -> x * x <= n)
            $ dropWhile (\x -> x * k < n) [1 ..]

import           Data.List
import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    let m = maxBound :: Int
    print $ f n k

f :: Int -> Int -> Int
-- x * y = n 1<=x<=k
f n k | null pds  = n
      | otherwise = head pds
  where
    pds =
        filter (\x -> mod n x == 0) . takeWhile (\x -> x * x <= n) $ dropWhile
            (\x -> x * k < n)
            (1 : 2 : [3, 5 ..])

import           Data.List
import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    let m = maxBound :: Int
    print $ f n k

f :: Int -> Int -> Int
-- n = x * y x is minimum then y is maximum
f n k | not . null $ divs = n `div` head divs
      | k >= n            = 1
      | otherwise         = n
  where
    divs = filter ((0 ==) . (n `mod`))
                  (2 : takeWhile (\x -> x * x <= n && x <= k) [3, 5 ..])

import           Data.List
import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    let m = maxBound :: Int
    print $ f n k

f :: Int -> Int -> Int
-- x * y = n 1<=x<=k
f n k | null pds  = n
      | otherwise = head pds
  where
    pds =
        filter (\x -> mod n x == 0) . takeWhile (\x -> x * x <= n) $ dropWhile
            (\x -> x * k < n)
            [1 ..]

import           Data.List
import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    let m = maxBound :: Int
    print $ f n k

f :: Int -> Int -> Int
-- n = x * y x is minimum then y is maximum
f n k | not . null $ divs = head divs
      | k >= n            = 1
      | otherwise         = n
  where
    divs = filter ((0 ==) . (n `mod`))
                  (takeWhile (\x -> x * x <= n && x <= k) [start ..])
    start = ceiling $ (fromIntegral n) / (fromIntegral k)

import           Data.List
import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    let m = maxBound :: Int
    print $ f n k

f :: Int -> Int -> Int
-- n = x * y x is minimum then y is maximum
f n k | not . null $ divs = head divs
      | otherwise         = n
  where
    divs = filter ((0 ==) . (n `mod`))
                  (takeWhile (\x -> x * x <= n && x <= k) [start ..])
    start = ceiling $ (fromIntegral n) / (fromIntegral k)

import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    print $ f n k

f :: Int -> Int -> Int
f n k | null pds  = n
      | otherwise = head pds
  where
    pds =
        filter (\x -> mod n x == 0) . takeWhile (\x -> x * x <= n) $ dropWhile
            (\x -> x * k < n)
            [1 ..]

import           Control.Monad

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

solve :: IO ()
solve = do
    [n, k] <- map read . words <$> getLine
    print $ f n k

f :: Int -> Int -> Int
f n k | null pds  = n
      | otherwise = minimum pds
  where
    pds =
        filter (\x -> mod n x == 0) . takeWhile (\x -> x * x <= n) $ dropWhile
            (\x -> x * k < n)
            [1 ..]

import Control.Monad (replicateM_)

getDivisors n limit = [x | x <- [1 .. limit], n `mod` x == 0]

getShovelType :: [Int] -> Int
getShovelType [n, k] =
    if length beforeSqrt == 0 then head afterSqrt
    else head beforeSqrt
    where
        limit = (round . sqrt . fromIntegral) n
        divisors = getDivisors n limit
        beforeSqrt = filter (\x -> n `div` x <= k) divisors
        afterSqrt = filter (\x -> n `div` x <= k) (map (\x -> n `div` x) divisors)

readLine :: IO [Int]
readLine = (map read) . words <$> getLine

main =
    read <$> getLine >>= \t ->
    replicateM_ t (getShovelType <$> readLine >>= print)

import Control.Monad ( replicateM_ )

readInput = map read . words <$> getLine

buyingShovels :: [Int] -> Int
buyingShovels [n, k] = head cands'
    where cands' = filter (\x -> n`mod`x==0 && n`div`x<=k) cands
          cands = [1..(ceiling.sqrt.fromIntegral $ n)] ++ [n]

main = do
    t <- read <$> getLine
    replicateM_ t (buyingShovels <$> readInput >>= print)


{-
f [] ['*'] _ = "YES"
f [] [] _ = "YES"
f _ [] _ = "NO"
f [] _ _ = "NO"
f xx@(x:xs) tt@(t:ts) dict
	|t==x = f xs ts dict
	|t=='?' && inDict =f xs ts dict
	|t=='*' && length xs<length ts = f xx ts dict
	|t=='*' && not inDict = f xs tt dict
	|t=='*' && elem x dict = f xx ts dict
	|otherwise = "NO"
	where inDict = elem x dict

extract (x:y:n:xs)=(x,y,read n::Int,xs)

solve (dict,template,n,xs)=map (\d->f d template dict ) $ take n xs

main=interact$unlines.solve.extract.lines

-}

import Control.Applicative( (<$>))
import Control.Monad( replicateM, forM_)

main = do
    goodLetters_ <- getLine
    expression_ <- getLine
    n_ <- readLn
    queries_ <- replicateM n_ getLine
    let
	isMatch [] [] = [True]
	isMatch "*" [] = [True]
	isMatch _ [] = [False]
	isMatch [] _ = [False]
	isMatch exp@(e:xpression) q@(c:cs) = case e of
	    '?'	-> if c `elem` goodLetters_
		    then isMatch xpression cs
		    else [False]
	    '*'	-> if c `elem` goodLetters_
		    then isMatch xpression q
		    else (isMatch xpression q)++(isMatch exp cs)
	    e	-> if e==c then isMatch xpression cs else [False]

	putStr' query = putStrLn $
			    if or $ isMatch expression_ query
				then "YES"
				else "NO"
    forM_ queries_ putStr'

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

main = do
  gs <- getLine
  p <- getLine
  n <- fmap readInt B.getLine
  qs <- replicateM n getLine
  putStr $ unlines $ map (\x -> if x then "YES" else "NO") $ solve gs p qs

solve gs pt = map (ok pt)
  where
    bs = ['a'..'z'] \\ gs
    ok [] [] = True
    ok "*" [] = True
    ok _ [] = False
    ok [] _ = False
    ok (p:ps) (q:qs)
      | p == q = ok ps qs
      | p == '?' = q `elem` gs && ok ps qs
      | p == '*' = ok ps (q:qs) || q `elem` bs && ok (p:ps) qs
      | otherwise = False

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

import Control.Monad( replicateM)

extract (x:y:n:xs)=(x,y,read n::Int,xs)

sel "YES" _ = "YES"
sel _ "YES" = "YES"
sel _ _ ="NO"
main=do
	dict<-getLine
	template<-getLine
	n<-readLn
	xs<-replicateM n getLine
	let
		f [] [] = "YES"
		f "*" [] = "YES"
		f _ [] = "NO"
		f [] _ = "NO"
		f exp@(e:xpression) q@(c:cs) = case e of
			'?'	-> if c `elem` dict
				then f xpression cs
				else "NO"
			'*'	-> if c `elem` dict
				then f xpression q
				else sel (f xpression q) (f exp cs)
			e	-> if e==c then f xpression cs else "NO"

		res=map (\d->f template d) xs
	mapM_ putStrLn $ res

import Control.Monad( replicateM)

extract (x:y:n:xs)=(x,y,read n::Int,xs)

main=do
	dict<-getLine
	template<-getLine
	n<-readLn
	xs<-replicateM n getLine
	let
		f [] [] = "YES"
		f "*" [] = "YES"
		f _ [] = "NO"
		f [] _ = "NO"
		f exp@(e:xpression) q@(c:cs) = case e of
			'?'	-> if c `elem` dict
				then f xpression cs
				else "NO"
			'*'	-> if c `elem` dict
				then f xpression q
				else (f exp cs)
			e	-> if e==c then f xpression cs else "NO"

		res=map (\d->f template d) xs
	mapM_ putStrLn $ res

import Control.Monad( replicateM)

extract (x:y:n:xs)=(x,y,read n::Int,xs)

main=do
	dict<-getLine
	template<-getLine
	n<-readLn
	xs<-replicateM n getLine
	let
		f [] [] = "YES"
		f "*" [] = "YES"
		f _ [] = "NO"
		f [] _ = "NO"
		f exp@(e:xpression) q@(c:cs) = case e of
			'?'	-> if c `elem` dict
				then f xpression cs
				else "NO"
			'*'	-> if c `elem` dict
				then f xpression q
				else (f xpression q)++(f exp cs)
			e	-> if e==c then f xpression cs else "NO"

		res=map (\d->f template d) xs
	mapM_ putStrLn $ res

f [] ['*'] _ = "YES"
f [] [] _ = "YES"
f _ [] _ = "NO"
f [] _ _ = "NO"
f xx@(x:xs) tt@(t:ts) dict
	|t==x = f xs ts dict
	|t=='?' && elem x dict =f xs ts dict
	|t=='*' && not (elem x dict) = f xs tt dict
	|t=='*' && elem x dict = f xx ts dict
	|otherwise = "NO"

extract (x:y:n:xs)=(x,y,read n::Int,xs)

solve (dict,template,n,xs)=map (\d->f d template dict ) $ take n xs

main=interact$unlines.solve.extract.lines

import Control.Applicative( (<$>))
import Control.Monad( replicateM, forM_)

main = do
    goodLetters_ <- getLine
    expression_ <- getLine
    n_ <- readLn
    queries_ <- replicateM n_ getLine
    let
	isMatch [] [] = [True]
	isMatch "*" [] = [True]
	isMatch _ [] = [False]
	isMatch [] _ = [False]
	isMatch exp@(e:xpression) q@(c:cs) = case e of
	    '?'	-> if c `elem` goodLetters_
		    then isMatch xpression cs
		    else [False]
	    '*'	-> if c `elem` goodLetters_
		    then isMatch xpression q
		    else (isMatch xpression cs)++(isMatch exp cs)
	    e'	-> if e'==c then isMatch xpression cs else [False]

	putStr' query = putStrLn $
			    if or $ isMatch expression_ query
				then "YES"
				else "NO"
    forM_ queries_ putStr'

import Control.Applicative( (<$>))
import Control.Monad( replicateM, forM_)

main = do
    goodLetters_ <- getLine
    expression_ <- getLine
    n_ <- readLn
    queries_ <- replicateM n_ getLine
    let
	isMatch "*" [] = [True]
	isMatch [] [] = [True]
	isMatch _ [] = [False]
	isMatch [] _ = [False]
	isMatch exp@(e:xpression) q@(c:cs) = case e of
	    '?'	-> if c `elem` goodLetters_
		    then isMatch xpression cs
		    else [False]
	    '*'	-> if c `elem` goodLetters_
		    then isMatch xpression q
		    else (isMatch xpression cs)++(isMatch exp cs)
	    e	-> if e==c then isMatch xpression cs else [False]

	putStr' query = putStrLn $
			    if or $ isMatch expression_ query
				then "YES"
				else "NO"
    forM_ queries_ putStr'


{-# OPTIONS_GHC -O2 #-}

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

main = do
    [[_, _, ax, bx], ays, bys, ls] <- fmap (map (map (fromIntegral . fst . fromJust . BS.readInt) . BS.words) . BS.lines) BS.getContents :: IO [[Double]]
    let ds = map (\ay -> dist (0, 0) (ax, ay)) ays
    let (len, i, j) = solve 1 1 ax bx ays bys ds ls []
    putStr $ show i ++ " " ++ show j
    where
        solve _ _ _ _ _ [] _ [] anss = minimum anss
        solve i j ax bx [ay] bys [d] ls anss = solve i j ax bx [ay, 10 ^ 10] bys [d, 10 ^ 10] ls anss
        solve i j ax bx (ay1:ay2:ays) (by:bys) (d1:d2:ds) (l:ls) anss = if d1 + dist (ax, ay1) (bx, by) >= d2 + dist (ax, ay2) (bx, by)
            then solve (i + 1) j ax bx (ay2:ays) (by:bys) (d2:ds) (l:ls) anss
            else solve i (j + 1) ax bx (ay1:ay2:ays) bys (d1:d2:ds) ls $ (d1 + dist (ax, ay1) (bx, by) + l, i, j):anss

dist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2

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

main = do
  let readInt =  fst . fromJust . C.readInt
  (n:m:input) <- fmap (map (readInt) . C.words) C.getContents
  let (u:v:a, input') = splitAt (n+2) $ map fromIntegral input
      (b, c) = splitAt m input'
      (ans, x, y) = minimum $ gao u v (zip [1 ..] a) (zip3 [1 ..] b c)
  putStrLn $ show x ++ " " ++ show y

hypot x y = sqrt $ x * x + y * y

gao u v a b = go a b
  where
    go _ [] = []
    go a ((j, r, d): t) = (dist l, i, j): go a' t
      where
        dist l = hypot u l + hypot (v - u) (r - l) + d
        a'@((i, l): _) = best a
        best [h] = [h]
        best l1@((_, h1): l2@((_, h2): t)) =
          if dist h2 <= dist h1 then best l2 else l1

{-# OPTIONS_GHC -O2 #-}

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

main = do
    [[_, _, ax, bx], ays, bys, ls] <- fmap (map (map (fromIntegral . fst . fromJust . BS.readInt) . BS.words) . BS.lines) BS.getContents
    let (len, i, j) = solve 1 1 ax bx ays bys ls []
    putStr $ show i ++ " " ++ show j
    where
        solve _ _ _ _ _ [] [] anss = minimum anss
        solve i j ax bx [ay] bys ls anss = solve i j ax bx [ay, 10 ^ 10] bys ls anss
        solve i j ax bx (ay1:ay2:ays) (by:bys) (l:ls) anss = if dist (0, 0) (ax, ay1) + dist (ax, ay1) (bx, by) >= dist (0, 0) (ax, ay2) + dist (ax, ay2) (bx, by)
            then solve (i + 1) j ax bx (ay2:ays) (by:bys) (l:ls) anss
            else solve i (j + 1) ax bx (ay1:ay2:ays) bys ls $ (dist (0, 0) (ax, ay1) + dist (ax, ay1) (bx, by) + l, i, j):anss

dist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2

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

main = do
  let readInt =  fst . fromJust . C.readInt
  (n:m:input) <- fmap (map (readInt) . C.words) C.getContents
  let (u:v:a, input') = splitAt (n+2) $ map fromIntegral input
      (b, c) = splitAt m input'
      (ans, x, y) = minimum $ gao u v (zip [1 ..] a) (zip3 [1 ..] b c)
  putStrLn $ show x ++ " " ++ show y

hypot x y = sqrt $ x * x + y * y

gao u v a b = go a b
  where
    go _ [] = []
    go a ((j, r, d): t) = (dist l, i, j): go a' t
      where
        dist l = hypot u l + hypot (v - u) (r - l) + d
        a'@((i, l): _) = best a
        best [h] = [h]
        best l1@((_, h1): l2@((_, h2): t)) =
          if dist h2 < dist h1 then l2 else l1


-- Codeforces Round #531 (B), Contest 1102, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.Function

main :: IO ()
main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  as <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine :: IO [Int]
  let ias = sorton snd $ zip [0..] as
      mink = maximum $ map length $ groupBy ((==) `on` snd) ias
      sortedAns = zipWith (\(i,a) c -> (i,c)) ias $ cycle [1..k]
      ans = map snd $ sorton fst sortedAns
  if mink <= k then do
    putStrLn "YES"
    putStrLn $ unwords $ map show ans
  else
    putStrLn "NO"

sorton f = sortBy (compare `on` f)

import Data.Function
import Data.Functor
import Data.List hiding (sortOn)
import qualified Data.Map as M

toList :: (Read a) => String -> [a]
toList = (map read) <$> words

main = do
    [n, k] <- toList <$> getLine :: IO [Int]
    as <- toList <$> getLine :: IO [Int]
    let bs = sortOn snd $ zip [0 .. ] as
        m = maximum $ map length $ groupBy ((==) `on` snd) bs
        cs = zipWith (\(x,_) y -> (x, y)) bs (cycle [1 .. k])
    if m > k then do
        putStrLn "NO"
    else do
        putStrLn "YES"
        putStrLn $ unwords $ map (show . snd) $ sortOn fst cs

sortOn :: (Ord b) => (a -> b) -> [a] -> [a]
sortOn f = sortBy (compare `on` f)

import Data.Functor
import qualified Data.List as L
import qualified Data.Map as M

toList :: (Read a) => String -> [a]
toList = (map read) <$> words

addIndex :: [Int] -> [(Int, Int)]
addIndex = zip [1 .. ]

sortByValue :: [(Int, Int)] -> [(Int, Int)]
sortByValue = L.sortBy (\(_,x) (_,y) -> compare x y)

colorize :: Int -> [(Int, Int)] -> [(Int, Int)]
colorize k xs = zip (map fst xs) (cycle [1..k])

sortByIndex :: [(Int, Int)] -> [(Int, Int)]
sortByIndex = L.sort

output :: [(Int, Int)] -> IO ()
output xs = do
    putStrLn "YES"
    putStrLn $ L.intercalate " " (map (show . snd) xs)

main = do
    (n, k) <- (\[e1, e2] -> (e1, e2)) <$> toList <$> getLine :: IO (Int, Int)
    arr <- toList <$> getLine :: IO [Int]
    if (maximum $ map length $ L.group $ L.sort arr) > k || (length arr) < k
    then
        putStrLn "NO"
    else
        output . sortByIndex $ colorize k (sortByValue $ addIndex arr)

    return ()


module Main where

work [] t=[]
work ('1':xs) 2='0':work xs 1
work ('1':xs) t='1':work xs 2
work ('0':xs) 1='0':work xs 0
work ('0':xs) t='1':work xs 1

run 1 = do
    l1 <- getLine
    l2 <- getLine
    let str=l2
    putStrLn $ work str 5

run x = do
    run 1
    run (x-1)

main = do
    l1 <- getLine
    let t = (read::String->Integer) l1
    run t

solve :: String -> String
solve = go '*'
    where go last [] = []
          go last (c : t)
            | succ c == last = '0' : go c t
            | otherwise      = '1' : go (succ c) t

main :: IO ()
main = interact (unlines . map solve . takeEven . tail . lines)
    where takeEven l = map snd $ filter (even . fst) (zip [1..] l)

solve :: String -> String
solve s = '1' : go (p $ head s) (tail s)
    where go last [] = []
          go last [c] = if p c == last then "0" else "1"
          go last (c : d : t)
            | p c == last = '0' : go c (d : t)
            | otherwise   = '1' : go (p c) (d : t)
          p '0' = '1'
          p '1' = '2'

main :: IO ()
main = interact (unlines . map solve . takeOdd . tail . lines)
    where takeOdd [] = []
          takeOdd [x] = []
          takeOdd (x : y : z) = y : takeOdd z

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

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

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

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

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

solve :: String -> String
solve s = solve' (-1) s
    where
        solve' :: Int -> String -> String
        solve' _ [] = []
        solve' 1 ('0':s) = '0' : solve' 0 s
        solve' _ ('0':s) = '1' : solve' 1 s
        solve' 2 ('1':s) = '0' : solve' 1 s
        solve' _ ('1':s) = '1' : solve' 2 s

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        s <- B8.getLine <&> B8.unpack . head . B8.words
        let answer = solve s
        putStrLn answer

solve :: String -> String
solve s = go (head s) s
    where go last [] = []
          go last [c] = if c == last then "1" else "0"
          go last (c : d : t)
            | p c == last = '0' : go c (d : t)
            | otherwise   = '1' : go (p c) (d : t)
          p '0' = '1'
          p '1' = '2'

main :: IO ()
main = interact (unlines . map solve . takeOdd . tail . lines)
    where takeOdd [] = []
          takeOdd [x] = []
          takeOdd (x : y : z) = y : takeOdd z

solve :: String -> String
solve [] = []
solve [c] = "0"
solve (c : d : t)
    | c == d    = '1' : '0' : solve t
    | otherwise = '0' : solve (d : t)

main :: IO ()
main = interact (unlines . map solve . takeOdd . tail . lines)
    where takeOdd [] = []
          takeOdd [x] = []
          takeOdd (x : y : z) = y : takeOdd z

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

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

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

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

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

solve :: String -> String
solve s = solve' (-1) s
    where
        solve' :: Int -> String -> String
        solve' _ [] = []
        solve' 0 ('0':s) = '1' : solve' 1 s
        solve' _ ('0':s) = '0' : solve' 0 s
        solve' 1 ('1':s) = '1' : solve' 2 s
        solve' _ ('1':s) = '0' : solve' 1 s

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        s <- B8.getLine <&> B8.unpack . head . B8.words
        let answer = solve s
        putStrLn answer


import Control.Monad

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

main :: IO()
main = do
    [t] <- getInts
    replicateM_ t routine

routine :: IO()
routine = do
    [n] <- getInts
    a <- getInts
    let evens = [z | z <- (zip a [0..]), even $ fst z]
        badevens_count = length $ filter (\x -> odd $ snd x) evens
        odds = [z | z <- (zip a [0..]), odd $ fst z]
        badodds_count = length $ filter (\x -> even $ snd x) odds
    if badevens_count /= badodds_count then
        print (-1)
    else
        print badevens_count

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

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

modifyArray a i f = writeArray a i =<< f <$> readArray a i

main = do
	t <- readInt
	mapM_ print =<< replicateM t solve

solve = do
	n <- readInt
	as <- readInts
	let
		evens = length $ filter odd $ map fst $ filter snd $ zip as $ cycle [ True, False ]
		odds = length $ filter even $ map fst $ filter snd $ zip as $ cycle [ False, True ]
	return $ if evens == odds
		then evens
		else -1

import Control.Monad
import Data.List

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

routine :: IO ()
routine = do
  _ <- getLine
  xs <- (map read.words) <$> getLine
  print $ solve xs

solve :: [Int] -> Int
solve xs = if ce == co then ce else -1
  where
    (e,o) = partition (even.snd) (zip xs [0..])
    (e',o') = (map fst e,map fst o)
    ce =length $ filter odd e'
    co = length $ filter even o'

main = do
  inputjar <- getLine
  let n = read inputjar :: Int
  solve n

solve :: Int -> IO ()
solve 0 = putStr ""
solve n = do
  _ <- getLine
  input <- getLine
  let list = read ("[" ++ map (\x -> if x == ' ' then ',' else x) input ++ "]") :: [Int]
  solveCase list
  solve (n - 1)

solveCase :: [Int] -> IO ()
solveCase xs = print $ if odd == even then odd else (-1)
  where
    odd = foldl (\acc i -> acc + if (xs !! i) `mod` 2 == 1 then 0 else 1) 0 [1, 3 .. length xs - 1]
    even = foldl (\acc i -> acc + if (xs !! i) `mod` 2 == 0 then 0 else 1) 0 [0, 2 .. length xs - 1]

import Data.Maybe (catMaybes)
import Data.List (sort, group)
import Control.Monad (replicateM_)

data Inversion = Even | Odd deriving (Eq, Ord)

f :: (Int, Int) -> Maybe Inversion
f (x,y) | even x && odd y = Just Even
        | odd x && even y = Just Odd
        | otherwise = Nothing

main = readLn >>= flip replicateM_ (getLine >> getLine >>= print . w . catMaybes . map f .  zip [0..] . map read . words)
    where w [] = 0
          w xs = case map length . group $ sort xs of
             [_] -> -1
             [a,b] -> if a==b then a else -1

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

process  e o  [] = if e==o then e else -1
process e o [a] | even a = process e o []
                |otherwise = process (e+1) o []

process e o (a:b:c) | even a && odd b = process e o c
                    | even a && even b = process e (o+1) c
		    | odd a && odd b = process (e+1) o c
		    | otherwise = process (e+1) (o+1) c

onecase = do
		getLine
		k<- map read <$> words <$> getLine ::IO [Int]
		print $ process 0 0 k

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

import Control.Monad

countOddEven [] o e l = (o, e, l)
countOddEven (a:t) o e l
  | a `mod` 2 == 0 = countOddEven t o (e + 1) (l + 1)
  | otherwise      = countOddEven t (o + 1) e (l + 1)

solve :: [Int] -> Int
solve lst =
  let
    (o, e, l) = countOddEven lst 0 0 0
  in
    if (abs (o - e)) /= l `mod` 2  then -1
    else
      let
        wrong = length (filter not (zipWith (\a b->a `mod` 2 /= b `mod` 2)[1..] lst))
      in
        if wrong `mod` 2 == 0 then wrong `div` 2 else -1

main = do
  n <- read <$> getLine
  a <- replicateM n (getLine >> getLine)
  let ainp = (map read) . words <$> a
  mapM_ (putStrLn . show . solve) $ ainp


import Control.Monad

solveRecursively :: (Char,String) -> Maybe String
solveRecursively (prev,x:(x2:xs))
  |prev == x = Nothing
  |x=='?' = fmap ((:) (decide [prev,x2])) (solveRecursively (decide [prev,x2],x2:xs))
  |otherwise = fmap ((:) x) (solveRecursively (x,x2:xs))
solveRecursively (prev,[x])
  |prev == x = Nothing
  |x=='?' = fmap ((:) (decide [prev])) (solveRecursively (decide [prev],[]))
  |otherwise =fmap ((:) x) (solveRecursively (x,[]))
solveRecursively _ = Just []

routine :: IO ()
routine = do
  str <- getLine
  case solveRecursively ('y',str) of
    Nothing -> putStrLn "-1"
    Just x -> putStrLn x

decide :: [Char] -> Char
decide li = head $ filter (`notElem` li) "abc"

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

import Control.Monad

main :: IO ()
main = do
  input <- getLine
  let linesToRead = read input
  tryDecorateString linesToRead

tryDecorateString :: Int -> IO ()
tryDecorateString 0 = pure ()
tryDecorateString n = do
  currentLine <- getLine
  if isStringBeautiful currentLine Nothing
  then putStrLn (reverse (decorateString currentLine []))
  else putStrLn "-1"
  tryDecorateString (n - 1)

alphabet :: [Char]
alphabet = ['a', 'b', 'c']

-- check that string doesn't contains any double characters
isStringBeautiful :: [Char] -> Maybe Char -> Bool
isStringBeautiful (x:xs) Nothing =
  if (length xs) == 0
  then True
  else isStringBeautiful xs (Just x)

isStringBeautiful (x:xs) (Just prevChar) =
  if x == prevChar && x /= '?'
  then False
  else isStringBeautiful xs (Just x)

isStringBeautiful [] _ = True

-- start for 1 elem
decorateString :: [Char] -> [Char] -> [Char]
decorateString word formattedWord =
  case word of
  (x:[]) -> case x of
    '?' -> case formattedWord of
      -- start iteration
      [] -> [anyChar]
      -- end of iteration
      (r:rs) -> allowedEnd:r:rs
    _ -> x:formattedWord
  (x:xs) -> case x of
    '?' -> case formattedWord of
      [] -> decorateString xs (allowedStart:[])
      (r:rs) -> decorateString xs (allowedMiddle:r:rs)
    _   -> decorateString xs (x:formattedWord)
  where
    anyChar = alphabet !! 0
    nextChar = word !! 1
    prevChar = head formattedWord
    allowedStart = (filter (/= nextChar) alphabet) !! 0
    allowedMiddle = (filter (\x -> x /= prevChar && x /= nextChar) alphabet) !! 0
    allowedEnd = (filter (/= prevChar) alphabet) !! 0

-- beautify string

tests :: [String]
tests = ["a???cb", "a??bbc", "a?b?c", "a??a"]

import Control.Monad

solve :: String -> String
solve str = newStr
  where
    indexed = zip [0..] str
    newStr = map f indexed
    f (index,char)
      | char /= '?' = char
      | index ==0 = decide [str!!(index+1)]
      | index ==length str-1 = decide [newStr!!(index-1)]
      | otherwise = decide [newStr!!(index-1),str!!(index+1)]

decide :: [Char] -> Char
decide li = head $ filter (`notElem` li) "abc"

routine :: IO ()
routine = do
  str <- getLine
  putStrLn $ solve str

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

import Control.Monad

main :: IO ()
main = do
  input <- getLine
  let linesToRead = read input
  tryDecorateString linesToRead

tryDecorateString :: Int -> IO ()
tryDecorateString 0 = pure ()
tryDecorateString n = do
  currentLine <- getLine
  if isStringBeautiful currentLine Nothing
  then putStrLn (decorateString currentLine [])
  else putStrLn "-1"
  tryDecorateString (n - 1)

alphabet :: [Char]
alphabet = ['a', 'b', 'c']

-- check that string doesn't contains any double characters
isStringBeautiful :: [Char] -> Maybe Char -> Bool
isStringBeautiful (x:xs) Nothing =
  if (length xs) == 0
  then True
  else isStringBeautiful xs (Just x)

isStringBeautiful (x:xs) (Just prevChar) =
  if x == prevChar && x /= '?'
  then False
  else isStringBeautiful xs (Just x)

isStringBeautiful [] _ = True

-- start for 1 elem
decorateString :: [Char] -> [Char] -> [Char]
decorateString word formattedWord =
  case word of
  (x:[]) -> case x of
    '?' -> case formattedWord of
      -- start iteration
      [] -> [anyChar]
      -- end of iteration
      (r:rs) -> allowedEnd:r:rs
    _ -> x:formattedWord
  (x:xs) -> case x of
    '?' -> case formattedWord of
      [] -> decorateString xs (allowedStart:[])
      (r:rs) -> decorateString xs (allowedMiddle:r:rs)
    _   -> decorateString xs (x:formattedWord)
  where
    anyChar = alphabet !! 0
    nextChar = word !! 1
    prevChar = head formattedWord
    allowedStart = (filter (/= nextChar) alphabet) !! 0
    allowedMiddle = (filter (\x -> x /= prevChar && x /= nextChar) alphabet) !! 0
    allowedEnd = (filter (/= prevChar) alphabet) !! 0

-- beautify string

tests :: [String]
tests = ["a???cb", "a??bbc", "a?b?c", "a??a"]