Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.

If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes).

NoteIn the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".

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

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

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

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"

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"

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

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

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"

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

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"


This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.Pikachu is a cute and friendly pokémon living in the wild pikachu herd.But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.First, Andrew counted all the pokémon — there were exactly $$$n$$$ pikachu. The strength of the $$$i$$$-th pokémon is equal to $$$a_i$$$, and all these numbers are distinct.As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $$$b$$$ from $$$k$$$ indices such that $$$1 \le b_1 < b_2 < \dots < b_k \le n$$$, and his army will consist of pokémons with forces $$$a_{b_1}, a_{b_2}, \dots, a_{b_k}$$$.The strength of the army is equal to the alternating sum of elements of the subsequence; that is, $$$a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \dots$$$.Andrew is experimenting with pokémon order. He performs $$$q$$$ operations. In $$$i$$$-th operation Andrew swaps $$$l_i$$$-th and $$$r_i$$$-th pokémon.Note: $$$q=0$$$ in this version of the task.Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.Help Andrew and the pokémon, or team R will realize their tricky plan!

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 3 \cdot 10^5, q = 0$$$) denoting the number of pokémon and number of operations respectively. The second line contains $$$n$$$ distinct positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) denoting the strengths of the pokémon. $$$i$$$-th of the last $$$q$$$ lines contains two positive integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) denoting the indices of pokémon that were swapped in the $$$i$$$-th operation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$q+1$$$ integers: the maximal strength of army before the swaps and after each swap.

NoteIn third test case we can build an army in such way: [1 2 5 4 3 6 7], its strength will be $$$5−3+7=9$$$.

import Data.Foldable
import Control.Monad

go = show . uncurry max . foldl' go (0, 0) . zip (cycle [True, False])
  where
    go (e, o) (True, x) = (max o $ e - x, max e $ o + x)
    go (e, o) (False, x) = (max o $ e + x, max e $ o - x)

main = mkMain go

mkMain f = do
  n <- readLn
  replicateM_ n $ do
    void $ getLine
    a <- map read . words <$> getLine
    putStrLn $ f a


You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions:   each integer must be greater than $$$0$$$;  the product of all $$$n-1$$$ numbers should be equal to $$$k$$$;  the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i < 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.

Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.

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

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


On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:   the sum of the costs of stuck pins;  the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.

The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.

Output the single number — the least fine you will have to pay.

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)


Moamen has an array of $$$n$$$ distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once:  Split the array into exactly $$$k$$$ non-empty subarrays such that each element belongs to exactly one subarray.  Reorder these subarrays arbitrary.  Merge the subarrays in their new order. A sequence $$$a$$$ is a subarray of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le |a_i| \le 10^9$$$). It is guaranteed that all numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test case, you should output a single string. If Moamen can sort the array in non-decreasing order, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower).

NoteIn the first test case, $$$a = [6, 3, 4, 2, 1]$$$, and $$$k = 4$$$, so we can do the operations as follows:   Split $$$a$$$ into $$$\{ [6], [3, 4], [2], [1] \}$$$.  Reorder them: $$$\{ [1], [2], [3,4], [6] \}$$$.  Merge them: $$$[1, 2, 3, 4, 6]$$$, so now the array is sorted. In the second test case, there is no way to sort the array by splitting it into only $$$2$$$ subarrays.As an example, if we split it into $$$\{ [1, -4], [0, -2] \}$$$, we can reorder them into $$$\{ [1, -4], [0, -2] \}$$$ or $$$\{ [0, -2], [1, -4] \}$$$. However, after merging the subarrays, it is impossible to get a sorted array.

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List (sort)
import Data.Maybe (fromJust)

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

testCase :: Scanner String
testCase = do
  n <- int
  k <- int
  xs <- n >< int
  return . bool "No" "Yes" $ splits xs < k

splits :: [Int] -> Int
splits xs =
  let ixs = map snd . sort $ zip xs [0 ..]
   in count (/= 1) $ zipWith (-) (tail ixs) ixs

count :: (a -> Bool) -> [a] -> Int
count f = length . filter f

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List (sort)
import Data.Maybe (fromJust)

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

testCase :: Scanner String
testCase = do
  n <- int
  k <- int
  xs <- n >< int
  return . bool "No" "Yes" $ splits xs <= k

splits :: [Int] -> Int
splits xs =
  let ixs = map snd . sort $ zip xs [0 ..]
   in count (/= 1) $ zipWith (-) (tail ixs) ixs

count :: (a -> Bool) -> [a] -> Int
count f = length . filter f

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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


Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.

The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj).

In a single line print a single integer — the answer to the problem.

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

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)

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


After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally?

The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.

Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw".

7
treasurehunt
threefriends
hiCodeforces

NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw.

import Data.List as List
import Data.Map.Strict as Map

getFreqLetter :: String -> Integer -> Integer
getFreqLetter s n =
  let cans = maximum $ Map.elems $ List.foldl (\mp c ->
                                      case Map.lookup c mp of
                                      Nothing -> Map.insert c 1 mp
                                      Just a  -> Map.insert c (a + 1) mp) Map.empty s in
  let len = fromIntegral (length s) :: Integer in
  if cans == len then
    if n == 1 then
      max (len - 1) 1
    else
      len
  else
    min (cans + n) len

main :: IO ()
main = do
  s <- getLine
  let n = read s :: Integer
  kuro <- getLine
  shiro <- getLine
  katie <- getLine
  let lst = [(getFreqLetter kuro n, "Kuro"), (getFreqLetter shiro n, "Shiro"), (getFreqLetter katie n, "Katie")]
  let slst = List.sort lst
  if fst (slst List.!! 2) == fst (slst List.!! 1) then
    putStrLn "Draw"
  else
    putStrLn $ snd (slst List.!! 2)

import Data.List as List
import Data.Map.Strict as Map

getFreqLetter :: String -> Int
getFreqLetter s =
  maximum $ Map.elems $ List.foldl (\mp c ->
                                      case Map.lookup c mp of
                                      Nothing -> Map.insert c 1 mp
                                      Just a  -> Map.insert c (a + 1) mp) Map.empty s

main :: IO ()
main = do
  s <- getLine
  let n = read s :: Int
  kuro <- getLine
  shiro <- getLine
  katie <- getLine
  let lst = [(getFreqLetter kuro, "Kuro"), (getFreqLetter shiro, "Shiro"), (getFreqLetter katie, "Katie")]
  let slst = List.sort lst
  if fst (slst List.!! 2) == fst (slst List.!! 1) then
    putStrLn "Draw"
  else
    putStrLn $ snd (slst List.!! 2)

import Data.List as List
import Data.Map.Strict as Map

getFreqLetter :: String -> Int -> Int
getFreqLetter s n =
  let cans = maximum $ Map.elems $ List.foldl (\mp c ->
                                      case Map.lookup c mp of
                                      Nothing -> Map.insert c 1 mp
                                      Just a  -> Map.insert c (a + 1) mp) Map.empty s in
  let len = length s in
  if cans == len then
    cans - (n `mod` 2)
  else min (cans + n) len

main :: IO ()
main = do
  s <- getLine
  let n = read s :: Int
  kuro <- getLine
  shiro <- getLine
  katie <- getLine
  let lst = [(getFreqLetter kuro n, "Kuro"), (getFreqLetter shiro n, "Shiro"), (getFreqLetter katie n, "Katie")]
  let slst = List.sort lst
  if fst (slst List.!! 2) == fst (slst List.!! 1) then
    putStrLn "Draw"
  else
    putStrLn $ snd (slst List.!! 2)

import Data.List as List
import Data.Map.Strict as Map

getFreqLetter :: String -> Integer -> Integer
getFreqLetter s n =
  let cans = maximum $ Map.elems $ List.foldl (\mp c ->
                                      case Map.lookup c mp of
                                      Nothing -> Map.insert c 1 mp
                                      Just a  -> Map.insert c (a + 1) mp) Map.empty s in
  let len = fromIntegral (length s) :: Integer in
  if cans == len then
    if (n `mod` 2 == 0) then
      len
    else
      if n >= len then
        len
      else len - 1
  else min (cans + n) len

main :: IO ()
main = do
  s <- getLine
  let n = read s :: Integer
  kuro <- getLine
  shiro <- getLine
  katie <- getLine
  let lst = [(getFreqLetter kuro n, "Kuro"), (getFreqLetter shiro n, "Shiro"), (getFreqLetter katie n, "Katie")]
  let slst = List.sort lst
  if fst (slst List.!! 2) == fst (slst List.!! 1) then
    putStrLn "Draw"
  else
    putStrLn $ snd (slst List.!! 2)

import Data.List as List
import Data.Map.Strict as Map

getFreqLetter :: String -> Int -> Int
getFreqLetter s n =
  let cans = maximum $ Map.elems $ List.foldl (\mp c ->
                                      case Map.lookup c mp of
                                      Nothing -> Map.insert c 1 mp
                                      Just a  -> Map.insert c (a + 1) mp) Map.empty s in
  min (cans + n) (length s)

main :: IO ()
main = do
  s <- getLine
  let n = read s :: Int
  kuro <- getLine
  shiro <- getLine
  katie <- getLine
  let lst = [(getFreqLetter kuro n, "Kuro"), (getFreqLetter shiro n, "Shiro"), (getFreqLetter katie n, "Katie")]
  let slst = List.sort lst
  if fst (slst List.!! 2) == fst (slst List.!! 1) then
    putStrLn "Draw"
  else
    putStrLn $ snd (slst List.!! 2)

import Data.List as List
import Data.Map.Strict as Map

getFreqLetter :: String -> Integer -> Integer
getFreqLetter s n =
  let cans = maximum $ Map.elems $ List.foldl (\mp c ->
                                      case Map.lookup c mp of
                                      Nothing -> Map.insert c 1 mp
                                      Just a  -> Map.insert c (a + 1) mp) Map.empty s in
  let len = fromIntegral (length s) :: Integer in
  if cans == len then
    cans - (n `mod` 2)
  else min (cans + n) len

main :: IO ()
main = do
  s <- getLine
  let n = read s :: Integer
  kuro <- getLine
  shiro <- getLine
  katie <- getLine
  let lst = [(getFreqLetter kuro n, "Kuro"), (getFreqLetter shiro n, "Shiro"), (getFreqLetter katie n, "Katie")]
  let slst = List.sort lst
  if fst (slst List.!! 2) == fst (slst List.!! 1) then
    putStrLn "Draw"
  else
    putStrLn $ snd (slst List.!! 2)


n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.You have to write a program which prints the number of the child to be eliminated on every step.

The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1). The next line contains k integer numbers a1, a2, ..., ak (1 ≤ ai ≤ 109).

Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.

NoteLet's consider first example:   In the first step child 4 is eliminated, child 5 becomes the leader.  In the second step child 2 is eliminated, child 3 becomes the leader.  In the third step child 5 is eliminated, child 6 becomes the leader.  In the fourth step child 6 is eliminated, child 7 becomes the leader.  In the final step child 1 is eliminated, child 3 becomes the leader.

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)

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

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


Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":  1st bracket is paired with 8th,  2d bracket is paired with 3d,  3d bracket is paired with 2d,  4th bracket is paired with 7th,  5th bracket is paired with 6th,  6th bracket is paired with 5th,  7th bracket is paired with 4th,  8th bracket is paired with 1st. Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:  «L» — move the cursor one position to the left,  «R» — move the cursor one position to the right,  «D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to). After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted). There are pictures illustrated several usages of operation "D" below.  All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.Polycarp is very proud of his development, can you implement the functionality of his editor?

The first line contains three positive integers n, m and p (2 ≤ n ≤ 500 000, 1 ≤ m ≤ 500 000, 1 ≤ p ≤ n) — the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even. It is followed by the string of n characters "(" and ")" forming the correct bracket sequence. Then follow a string of m characters "L", "R" and "D" — a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.

Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.

NoteIn the first sample the cursor is initially at position 5. Consider actions of the editor:  command "R" — the cursor moves to the position 6 on the right;  command "D" — the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;  command "L" — the cursor moves to the position 4 on the left;  command "D" — the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1. Thus, the answer is equal to ().

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

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)


A country called Flatland is an infinite two-dimensional plane. Flatland has n cities, each of them is a point on the plane.Flatland is ruled by king Circle IV. Circle IV has 9 sons. He wants to give each of his sons part of Flatland to rule. For that, he wants to draw four distinct straight lines, such that two of them are parallel to the Ox axis, and two others are parallel to the Oy axis. At that, no straight line can go through any city. Thus, Flatland will be divided into 9 parts, and each son will be given exactly one of these parts. Circle IV thought a little, evaluated his sons' obedience and decided that the i-th son should get the part of Flatland that has exactly ai cities.Help Circle find such four straight lines that if we divide Flatland into 9 parts by these lines, the resulting parts can be given to the sons so that son number i got the part of Flatland which contains ai cities.

The first line contains integer n (9 ≤ n ≤ 105) — the number of cities in Flatland. Next n lines each contain two space-separated integers: xi, yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th city. No two cities are located at the same point. The last line contains nine space-separated integers: .

If there is no solution, print a single integer -1. Otherwise, print in the first line two distinct real space-separated numbers: x1, x2 — the abscissas of the straight lines that are parallel to the Oy axis. And in the second line print two distinct real space-separated numbers: y1, y2 — the ordinates of the straight lines, parallel to the Ox. If there are multiple solutions, print any of them.  When the answer is being checked, a city is considered to lie on a straight line, if the distance between the city and the line doesn't exceed 10 - 6. Two straight lines are considered the same if the distance between them doesn't exceed 10 - 6.

NoteThe solution for the first sample test is shown below:  The solution for the second sample test is shown below:  There is no solution for the third sample test.

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
import Control.Monad
import Data.Array.Unboxed
import Data.Function
import Data.List
import Data.Maybe
import Data.Ord
import System.Exit
import Text.Printf
import qualified Data.ByteString.Char8 as C

pairs :: [a] -> [(a, a)]
pairs (x:y:z) = (x, y): pairs z
pairs _ = []

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

groupBy' :: Ord b => (a -> b) -> [a] -> [[a]]
groupBy' f = groupBy ((==) `on` f) . sortBy (comparing f)

type Arr = UArray Int Int

listArray' :: [Int] -> Arr
listArray' a = listArray (0, length a - 1) a

lowerBound :: Arr -> Int -> Int
lowerBound a x = go s $ t + 1
  where
    (s, t) = bounds a
    go l r
      | l == r    = l
      | otherwise = if a!m >= x then go l m else go (m + 1) r
      where
        m = (l + r) `div` 2

gao :: Arr -> [Int] -> Maybe [Int]
gao a xs = go (scanl1 (+) xs) [s]
  where
    (s, t) = bounds a
    go [] is = Just $ reverse is
    go (x:y) is =
      if i <= t && a!i == x
        then go y $ succ i:is
        else Nothing
      where
        i = lowerBound a x

data Node
  = Empty
  | Branch Int Int Arr Node Node

build :: Int -> Int -> [(Int, Int)] -> Node
build _ _ [] = Empty
build l r a = Branch l r (listArray' $ map snd a) bl br
  where
    m = (l + r) `div` 2
    (al, ar) = partition ((<m) . fst) a
    bl = build l m al
    br = build m r ar

query :: Node -> (Int, Int) -> (Int, Int) -> Int
query root (xl, xr) (yl, yr) = go root
  where
    go Empty = 0
    go (Branch l r a bl br)
      | l' == l && r' == r  = lowerBound a yr - lowerBound a yl
      | l' < r'             = go bl + go br
      | otherwise           = 0
      where
        l' = max l xl
        r' = min r xr

gen :: [Int] -> [[Int]]
gen [] = [[]]
gen a = concat [map (sum i:) $ gen j | (i, j) <- choose (3::Int) a [] []]
  where
    choose 0 k     i j = [(i, j ++ k)]
    choose _ []    _ _ = []
    choose n (h:t) i j = choose (n - 1) t (h:i) j ++ choose n t i (h:j)

main :: IO ()
main = do
  (n:input) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  let (xy, z) = splitAt (2 * n) input

      (x, y) = unzip $ pairs xy
      xs = listArray' $ uniq x
      ys = listArray' $ uniq y
      p = [(lowerBound xs i, lowerBound ys j) | (i, j) <- pairs xy]

      countBy f = scanl1 (+) . map length . groupBy' f
      q = uniq $ gen z
      cx = listArray' $ countBy fst p
      qx = catMaybes $ map (gao cx) $ q
      cy = listArray' $ countBy snd p
      qy = catMaybes $ map (gao cy) $ q

      tree = build 0 (succ $ maximum $ map fst p) $ sortBy (comparing snd) p
      r = sort z

  forM_ (groupBy' (!!1) qx) $ \qx' -> do
    forM_ (groupBy' (!!1) qy) $ \qy' -> do
      when (query tree (0, qx'!!0!!1) (0, qy'!!0!!1) `elem` r) $ do
        forM_ qx' $ \i -> do
          forM_ qy' $ \j -> do
            let r' = [query tree rx ry | rx <- zip i $ tail i, ry <- zip j $ tail j]
            when (sort r' == r) $ do
              forM_ [xs!(i!!1), xs!(i!!2), ys!(j!!1), ys!(j!!2)] $ \k -> do
                printf "%.10f\n" (fromIntegral k - 0.5 :: Double)
              exitSuccess

  putStrLn "-1"


One day, Ahmed_Hossam went to Hemose and said "Let's solve a gym contest!". Hemose didn't want to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract him. Sadly, Ahmed can't solve it... Could you help him?There is an Agent in Valorant, and he has $$$n$$$ weapons. The $$$i$$$-th weapon has a damage value $$$a_i$$$, and the Agent will face an enemy whose health value is $$$H$$$.The Agent will perform one or more moves until the enemy dies.In one move, he will choose a weapon and decrease the enemy's health by its damage value. The enemy will die when his health will become less than or equal to $$$0$$$. However, not everything is so easy: the Agent can't choose the same weapon for $$$2$$$ times in a row.What is the minimum number of times that the Agent will need to use the weapons to kill the enemy?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 10^5)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$H$$$ $$$(2 \leq n \leq 10^3, 1 \leq H \leq 10^9)$$$ — the number of available weapons and the initial health value of the enemy. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$ — the damage values of the weapons. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the minimum number of times that the Agent will have to use the weapons to kill the enemy.

NoteIn the first test case, the Agent can use the second weapon, making health value of the enemy equal to $$$4-7=-3$$$. $$$-3 \le 0$$$, so the enemy is dead, and using weapon $$$1$$$ time was enough.In the second test case, the Agent can use the first weapon first, and then the second one. After this, the health of enemy will drop to $$$6-4-2 = 0$$$, meaning he would be killed after using weapons $$$2$$$ times.In the third test case, the Agent can use the weapons in order (third, first, third), decreasing the health value of enemy to $$$11 - 7 - 2 - 7 = -5$$$ after using the weapons $$$3$$$ times. Note that we can't kill the enemy by using the third weapon twice, as even though $$$11-7-7<0$$$, it's not allowed to use the same weapon twice in a row.

import Control.Monad
import Data.List

-- k a + (k-1) b >= c
-- min k ?
-- k a + k b - b >= c
-- k (a+b) >= c + b
-- k >= (c+b)/(a+b)

calc :: [Int] -> Int -> Int -> Int
calc lst n h =
  let [a,b] = take 2 $ sortBy (flip compare) lst
      k1 = (h+b) `div` (a+b) + (if ((h+b) `mod` (a+b)) == 0 then 0 else 1)
      k = max 1 k1
  in
    if ((k-1)*a+(k-1)*b) >= h then 2*(k-1)
    else 2*k-1
    --2*k-1

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [n,h] = map read $ words line
    line <- getLine
    let w = map read $ words line
    --print [n,h]
    --print w
    print $ calc w n h


Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $$$n$$$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements. Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is $$$0$$$, and removing $$$i$$$-th character increases the ambiguity by $$$a_i$$$ (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still $$$4$$$ even though you delete it from the string had).Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the statement. The second line contains one string $$$s$$$ of length $$$n$$$, consisting of lowercase Latin letters — the statement written by Vasya. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 998244353$$$).

Print minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.

NoteIn the first example, first two characters are removed so the result is ardh.In the second example, $$$5$$$-th character is removed so the result is hhzawde.In the third example there's no need to remove anything.

solve [] [] = [0, 0, 0, 0]
solve s a =
    let ans = solve (tail s) (tail a)
    in [ans!!0 + if (head s) == 'd' then (head a) else 0,
        min (ans!!1 + if (head s) == 'r' then (head a) else 0) (ans!!0),
        min (ans!!2 + if (head s) == 'a' then (head a) else 0) (ans!!1),
        min (ans!!3 + if (head s) == 'h' then (head a) else 0) (ans!!2)]

main = do
    _ <- getLine
    s <- getLine
    a <- getLine
    print . minimum $ solve s (map read $ words a)


Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $$$s$$$ of length $$$n$$$.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $$$s$$$.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $$$s$$$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2 \cdot t$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $$$-1$$$, if it is impossible.

5
8
abcaacab
6
xyzxyz
4
abba
8
rprarlap
10
khyyhhyhky

NoteIn the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.In the third test case, you don't have to erase any symbols because the string is already a palindrome.

{-# OPTIONS -Wall #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad
import Data.Ord

main :: IO ()
main = do
    numTests <- readLn
    replicateM_ numTests $ do
        _ :: Int <- readLn
        s :: String <- getLine
        case solve s of
          Nothing -> print (-1 :: Int)
          Just k -> print k

solve :: String -> Maybe Int
solve s = fmap getDown $ maximum $ map (fmap Down . solveWith s) ['a'..'z']

solveWith :: String -> Char -> Maybe Int
solveWith s c = go 0 (length s - 1) s (reverse s) 0
  where
      go :: Int -> Int -> String -> String -> Int -> Maybe Int
      go i j (a:as) (b:bs) k
        | i >= j = Just k
        | a == b = go (i + 1) (j - 1) as bs k
        | a == c = go (i + 1) j as (b:bs) (k + 1)
        | b == c = go i (j - 1) (a:as) bs (k + 1)
        | otherwise = Nothing


A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand. One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.

The first line indicates the door through which the very important person entered the elevator. It contains "front" if the person enters the elevator through the front door and "back" if he entered the elevator through the back door. The second line contains integer a (1 ≤ a ≤ 2) which denotes the number of the rail at which the person was holding.

Print character "R" if the VIP is right-handed or "L" if he is left-handed.

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

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

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


Polycarp has a string $$$s$$$ consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string $$$s$$$ from left to right and for each letter Polycarp considers its number in the alphabet:  if the letter number is single-digit number (less than $$$10$$$), then just writes it out;  if the letter number is a two-digit number (greater than or equal to $$$10$$$), then it writes it out and adds the number 0 after. For example, if the string $$$s$$$ is code, then Polycarp will encode this string as follows:  'c' — is the $$$3$$$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3);  'o' — is the $$$15$$$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150);  'd' — is the $$$4$$$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504);  'e' — is the $$$5$$$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string $$$t$$$ resulting from encoding the string $$$s$$$. Your task is to decode it (get the original string $$$s$$$ by $$$t$$$).

The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. The descriptions of the test cases follow. The first line of description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the given code. The second line of the description of each test case contains a string $$$t$$$ of length $$$n$$$ — the given code. It is guaranteed that there exists such a string of lowercase Latin letters, as a result of encoding which the string $$$t$$$ is obtained.

For each test case output the required string $$$s$$$ — the string that gives string $$$t$$$ as the result of encoding. It is guaranteed that such a string always exists. It can be shown that such a string is always unique.

code
aj
abacaba
ll
codeforces
aaaak
aaaaj
aaaaa
zf

NoteThe first test case is explained above.In the second test case, the answer is aj. Indeed, the number of the letter a is equal to $$$1$$$, so 1 will be appended to the code. The number of the letter j is $$$10$$$, so 100 will be appended to the code. The resulting code is 1100.There are no zeros in the third test case, which means that the numbers of all letters are less than $$$10$$$ and are encoded as one digit. The original string is abacaba.In the fourth test case, the string $$$s$$$ is equal to ll. The letter l has the number $$$12$$$ and is encoded as 120. So ll is indeed 120120.

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

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

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