import Control.Applicative

func _ 10 _ _ _ _ = 0
func _ _ 10 _ _ _ = 0
func _ _ _ 10 _ _ = 0
func _ _ _ _ 10 _ = 0
func n a b c d cur = if a+b+c+d == n
                    then 1
                    else if a+b+c+d>n
                        then 0
                        else case cur of
                            0 -> (func n (a+1) b c d cur) + (func n a b c d (cur+1))
                            1 -> (func n a (b+1) c d cur) + (func n a b c d (cur+1))
                            2 -> (func n a b (c+1) d cur) + (func n a b c d (cur+1))
                            3 -> (func n a b c (d+1) cur) + (func n a b c d (cur+1))
                            _ -> 0

func' n = func n 0 0 0 0 0

main=do{
    n <- map (read::String->Int) . lines <$> getContents;
    mapM_ print $ map func' n
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Sum of 4 Integers

Write a program which reads an integer n and identifies the number of combinations of a, b, c and d (0 ≤ a, b, c, d ≤ 9) which meet the following equality:

a + b + c + d = n

For example, for n = 35, we have 4 different combinations of (a, b, c, d): (8, 9, 9, 9), (9, 8, 9, 9), (9, 9, 8, 9), and (9, 9, 9, 8).

Input

The input consists of several datasets. Each dataset consists of n (1 ≤ n ≤ 50) in a line. The number of datasets is less than or equal to 50.

Output

Print the number of combination in a line.

Sample Input

35
1

Output for the Sample Input

4
4

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


import Data.String
import Control.Applicative

main = do
        x <- words <$> getContents
        mapM print (map solve (map read x))

range :: [Int]
range = [0..9]

allList :: [[Int]]
allList = [[a, b, c, d] | a<-range, b<-range, c<-range, d<-range]

solve :: Int -> Int
solve n = length  [y | y<-allList, (foldr (+) 0 y) == n]


main = getContents >>= mapM_ (putStrLn . fout . prime_number . fin) . lines
fin = read
fout = show
prime_number n = length (takeWhile (<= n) primes)
primes = sieve [2..]
 where sieve (p:xs) = p : sieve [x | x<-xs, (mod x p) /= 0]

Prime Number

Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Input

Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.

The number of datasets is less than or equal to 30.

Output

For each dataset, prints the number of prime numbers.

Sample Input

10
3
11

Output for the Sample Input

4
2
5


main = getContents >>= mapM_ (print . maximum_sum_seq) . reverse . fin [] . map read . init . lines
fin acc [] = acc
fin acc (n:ns) = fin ((take (fromIntegral n) ns):acc) (drop (fromIntegral n) ns)
maximum_sum_seq ns = max (maximum frombot - minimum frombot) (maximum ns')
 where
  ns' = scanl (+) 0 ns
  frombot = dropWhile (/= minimum ns') ns'

Maximum Sum Sequence

Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence.

Input

The input consists of multiple datasets. Each data set consists of:

n
a1
a2
.
.
an

You can assume that 1 ≤ n ≤ 5000 and -100000 ≤ ai ≤ 100000.

The input end with a line consisting of a single 0.

Output

For each dataset, print the maximum sum in a line.

Sample Input

7
-5
-1
6
4
9
-6
-7
13
1
2
3
2
-2
-1
1
2
3
2
1
-2
1
3
1000
-200
201
0

Output for the Sample Input

19
14
1001


import Control.Applicative

import Control.Monad
    (replicateM, when)

type Set = [Int]

type Problem = (Int, Set)

type Result = Int

solve :: Problem -> Result

solve (n, set)
    = maximum subs where
        subs = [maximum [sum $ take y $ drop x set | y <- [1..(n - x)]] | x <- [0..(n - 1)]]

output :: Result -> String

output
    = show

input :: Int -> IO Set

input n
    = replicateM n $ read <$> getLine

check :: IO Int

check
    = read <$> getLine

main :: IO ()

main
    = do
        n <- check
        when (n /= 0) $ do
            set <- input n
            putStrLn $ output $ solve (n, set)
            main


import Data.List
import Data.IntMap (singleton, (!), keys, elems, unionWith, filterWithKey, mapKeys)
import qualified Data.IntMap as M

splitOn c xs
 | null xs = []
 | head xs == c = splitOn c (tail xs)
 | otherwise = (takeWhile (/= c)) xs : splitOn c (dropWhile (/= c) xs)

main = interact $ unlines . numbering . map (show' . thief) . read' . lines
 where
  read' ("0":_) = []
  read' (w:n:xs) = (read w, parse_vw $ take (read n) xs) : read' (drop (read n) xs)
   where parse_vw = map (map read . splitOn ',')
  show' (v,w) = show v ++ "\n" ++ show w
  numbering = zipWith (++) ["Case " ++ show n ++ ":\n" | n<-[1..]]

thief (max_weight, treasures) = dp (singleton 0 0) (sort treasures)
 where
  dp im [] = (im!k, k)
   where k = minimum $ keys $ M.filter (== (maximum $ elems im)) im
  dp im ([v,w]:vws) = dp (im' `seq` unionWith max im im') vws
   where im' = filterWithKey (\k _-> k<=max_weight) $ M.map (+v) $ mapKeys (+w) im

泥棒

宝物がたくさん収蔵されている博物館に、泥棒が大きな風呂敷を一つだけ持って忍び込みました。盗み出したいものはたくさんありますが、風呂敷が耐えられる重さが限られており、これを超えると風呂敷が破れてしまいます。そこで泥棒は、用意した風呂敷を破らず且つ最も価値が高くなるようなお宝の組み合わせを考えなくてはなりません。

風呂敷が耐えられる重さ W、および博物館にある個々のお宝の価値と重さを読み込んで、重さの総和が W を超えない範囲で価値の総和が最大になるときの、お宝の価値総和と重さの総和を出力するプログラムを作成してください。ただし、価値の総和が最大になる組み合わせが複数あるときは、重さの総和が小さいものを出力することとします。

Input

複数のデータセットが与えられます。各データセットは以下のような形式で与えられます。

W
N
v1,w1
v2,w2
:
vN,wN

１行目に風呂敷の耐えられる重さを表す整数 W (W ≤ 1,000)、２行目にお宝の数 N (1 ≤ N ≤ 1,000) が与えられます。続く N 行に i 番目のお宝の価値を表す整数 vi (0 ≤ vi ≤ 10,000) とその重さを表す整数 wi (0 ≤ wi ≤ W) の組がそれぞれ１行に与えられます。

W が 0 のとき入力の最後とします。データセットの数は 50 を超えません。

Output

各データセットに対して以下のように出力して下さい。

Case データセットの番号:
風呂敷に入れたお宝の価値総和
そのときのお宝の重さの総和

Sample Input

50
5
60,10
100,20
120,30
210,45
10,4
50
5
60,10
100,20
120,30
210,45
10,4
0

Output for the Sample Input

Case 1:
220
49
Case 2:
220
49


main = interact $ unlines . map (unwords . map show . prime2 . read) . lines

prime2 n = [last under, head (tail over)]
 where (under,over) = break (>=n) primes

primes = 2:3:[x | i<-[1..], j<-[-1,1], let x = 6*i+j, isPrime x]
 where isPrime n = null [i | i<-takeWhile (\x -> x*x <= n) primes, rem n i == 0]

素数 II

素数というのは、1 よりも大きくそれ自身か 1 でしか割りきれない整数をいいます。例えば、2 は、2 と 1 でしか割り切れないので素数ですが、12 は、12 と 1 のほかに、2, 3, 4, 6 で割りきれる数なので素数ではありません。

整数 n を入力したとき、n より小さい素数のうち最も大きいものと、n より大きい素数のうち最も小さいものを出力するプログラムを作成してください。

Input

複数のデータセットが与えられます。各データセットに n (3 ≤ n ≤ 50,000) が１行に与えられます。

データセットの数は 50 を超えません。

Output

各データセットに対して、n より小さい素数のうち最大のものと、n より大きい素数のうち最小のものを１つのスペースで区切って１行に出力して下さい。

Sample Input

19
3517

Output for the Sample Input

17 23
3511 3527


import Data.List

ans' :: Int -> [Int] -> Int -> Int
ans' 1 n s =
  if elem s n
  then 1
  else 0

ans' n num s =
  let max' = maximum num
      min' = minimum num
      smax = max' * ( div ( (n+1) * n ) 2 )
      smin = min' * ( div ( (n+1) * n ) 2 )
      num' = filter (\x -> s > x * n) num
  in
    -- Wrong Anser
    if s > smax || s < smin
    then 0
    else if num' == []
         then 0
         else sum $ map (\v -> ans' (n-1) (delete v num) (s - n*v) ) num'

    -- Time Limit Exceeded
    -- if num' == []
    -- then 0
    -- else sum $ map (\v -> ans' (n-1) (delete v num) (s - n*v) ) num'

ans [n,s] =
  ans' n [0..9] s

main = do
  c <- getContents
  let i = map (map read) $ map words $ lines c
      o = map ans i
  mapM_ print o

Combination of Number Sequences

0 から 9 までの整数を使った n 個の数の並び k1, k2, ..., kn を考えます。正の整数 n と s を読み込んで、

k1 + 2 × k2 + 3 × k3 + ... + n × kn = s

となっているような n 個の数の並びが何通りあるかを出力するプログラムを作成してください。ただし、1 つの「n 個の数の並び」には同じ数が 2 回以上現われないものとします。

Input

入力は複数のデータセットからなります。各データセットとして、n (1 ≤ n ≤ 10) と s (0 ≤ s ≤ 10,000)が空白区切りで１行に与えられます。

データセットの数は 100 を超えません。

Output

データセットごとに、n 個の整数の和が s になる組み合わせの個数を１行に出力します。

Sample Input

3 10
3 1

Output for the Sample Input

8
0


mymin x y = if x>y then y else x
mymax x y = if x>y then x else y

cases n 2
    | 2000<n    = 0
    | n<=1000   = n+1
    | otherwise = (mymax 1000 (n-1000))-(mymin 1000 (n-1000))+1
cases n num
    | 1000*num<n = 0
    | otherwise  = sum $ map (\x->cases (n-x) (num-1)) [0..(mymin n 1000)]

solve n = do
    print $ cases n 4

main = do
    ss<-getContents
    mapM_ solve $ map (\x->read x::Int) $ lines ss

４つの整数の和 II

4,000 以下の正の整数 n を入力し、0 〜 1000 の範囲の整数 a, b, c, d の組で

a + b + c + d = n

を満たすものの組み合わせ数を出力するプログラムを作成して下さい。

Input

複数のデータセットが与えられます。各データセットに n が１行に与えられます。入力の最後まで処理して下さい。

データセットの数は 50 を超えません。

Output

各データセットごとに、a, b, c, d の組み合わせの個数を１行に出力して下さい。

Sample Input

2
3
35

Output for the Sample Input

10
20
8436


import Control.Monad
import Data.Functor

import qualified Data.Array as Array

main :: IO ()
main = do
    n <- readLn :: IO Int
    if n == 0 then return ()
    else do
        salesData <- replicateM n $ do
            [i, p, q] <- map read <$> words <$> getLine :: IO [Int]
            return (i, p*q)
        let salesArray = Array.accumArray (+) 0 (1, 4000) salesData
            ids = map fst . filter ((<=) 1000001 . snd) $ Array.assocs salesArray
        if null ids then putStrLn "NA"
        else mapM_ print ids
        main

Sale Result

There is data on sales of your company. Your task is to write a program which identifies good workers.

The program should read a list of data where each item includes the employee ID i, the amount of sales q and the corresponding unit price p. Then, the program should print IDs of employees whose total sales proceeds (i.e. sum of p × q) is greater than or equal to 1,000,000 in the order of inputting. If there is no such employees, the program should print "NA". You can suppose that n < 4000, and each employee has an unique ID. The unit price p is less than or equal to 1,000,000 and the amount of sales q is less than or equal to 100,000.

Input

The input consists of several datasets. The input ends with a line including a single 0. Each dataset consists of:

n (the number of data in the list)
i p q
i p q
:
:
i p q

Output

For each dataset, print a list of employee IDs or a text "NA"

Sample Input

4
1001 2000 520
1002 1800 450
1003 1600 625
1001 200 1220
2
1001 100 3
1005 1000 100
2
2013 5000 100
2013 5000 100
0

Output for the Sample Input

1001
1003
NA
2013


import Control.Applicative
import Control.Monad
import Control.Monad.ST
import qualified Data.ByteString as BS
import Data.Functor
import Data.Function
import Data.Monoid
import Data.Maybe
import Data.List
import qualified Data.Foldable as Foldable
import qualified Data.Set as Set
--import qualified Data.Sequence as Sequence
import Data.List.Split
import Data.Bits
import Data.Char
import Data.Ix
import Data.Ratio
import Data.Ord
import Data.Tuple
--import Data.Array
--import Data.Array.Unboxed
import Data.Array.IArray
import Data.Array.MArray
import Data.Array.IO
import Data.Array.ST
import Data.IORef
import Data.STRef
-- import System.IO.Unsafe

-- templete
readInt = read :: String -> Int
readInteger = read :: String -> Integer
readDouble = read :: String -> Double
getInt = readLn :: IO Int
getInts = map readInt . words <$> getLine
getInteger = readLn :: IO Integer
getIntegers = map readInteger . words <$> getLine
getDouble = readLn :: IO Double
sjoin :: (Show a) => [a] -> String
sjoin = unwords . map show
cond :: a -> a -> Bool -> a
cond t f c = if c then t else f
apply2 :: (a -> a -> b) -> [a] -> b
apply2 f [x,y] = f x y
apply3 :: (a -> a -> a -> b) -> [a] -> b
apply3 f [x,y,z] = f x y z
apply4 :: (a -> a -> a -> a -> b) -> [a] -> b
apply4 f [x,y,z,w] = f x y z w
fnTuple :: (a -> b, a -> c) -> a -> (b, c)
fnTuple (f,g) a = (f a, g a)
replace :: (Eq a) => a -> a -> [a] -> [a]
replace x y = map (\z -> if z==x then y else z)
binMap :: (a -> a -> b) -> [a] -> [b]
binMap f (x:xs@(y:_)) = f x y : binMap f xs
binMap _ _ = []
splitRec :: Int -> [a] -> [[a]]
splitRec _ [] = []
splitRec n xs = let (y,ys) = splitAt n xs in y : splitRec n ys
infixl 7 `divCeil`
divCeil :: Integral a => a -> a -> a
x `divCeil` y = (x+y-1) `div` y
coverC :: Ord a => (a, a) -> a -> Bool
coverC (l,r) x = l<=x && x<=r
coverH :: Ord a => (a, a) -> a -> Bool
coverH (l,r) x = l<=x && x<r
-- templete

b 'A' = [0,0,0,0,0]
b 'B' = [0,0,0,0,1]
b 'C' = [0,0,0,1,0]
b 'D' = [0,0,0,1,1]
b 'E' = [0,0,1,0,0]
b 'F' = [0,0,1,0,1]
b 'G' = [0,0,1,1,0]
b 'H' = [0,0,1,1,1]
b 'I' = [0,1,0,0,0]
b 'J' = [0,1,0,0,1]
b 'K' = [0,1,0,1,0]
b 'L' = [0,1,0,1,1]
b 'M' = [0,1,1,0,0]
b 'N' = [0,1,1,0,1]
b 'O' = [0,1,1,1,0]
b 'P' = [0,1,1,1,1]
b 'Q' = [1,0,0,0,0]
b 'R' = [1,0,0,0,1]
b 'S' = [1,0,0,1,0]
b 'T' = [1,0,0,1,1]
b 'U' = [1,0,1,0,0]
b 'V' = [1,0,1,0,1]
b 'W' = [1,0,1,1,0]
b 'X' = [1,0,1,1,1]
b 'Y' = [1,1,0,0,0]
b 'Z' = [1,1,0,0,1]
b ' ' = [1,1,0,1,0]
b '.' = [1,1,0,1,1]
b ',' = [1,1,1,0,0]
b '-' = [1,1,1,0,1]
b '\'' =[1,1,1,1,0]
b '?' = [1,1,1,1,1]
toBin s = concat $ map b s

d (1:0:1:s) = ' ' : d s
d (0:0:0:0:0:0:s) = '\'' : d s
d (0:0:0:0:1:1:s) = ',' : d s
d (1:0:0:1:0:0:0:1:s) = '-' : d s
d (0:1:0:0:0:1:s) = '.' : d s
d (0:0:0:0:0:1:s) = '?' : d s
d (1:0:0:1:0:1:s) = 'A' : d s
d (1:0:0:1:1:0:1:0:s) = 'B' : d s
d (0:1:0:1:s) = 'C' : d s
d (0:0:0:1:s) = 'D' : d s
d (1:1:0:s) = 'E' : d s
d (0:1:0:0:1:s) = 'F' : d s
d (1:0:0:1:1:0:1:1:s) = 'G' : d s
d (0:1:0:0:0:0:s) = 'H' : d s
d (0:1:1:1:s) = 'I' : d s
d (1:0:0:1:1:0:0:0:s) = 'J' : d s
d (0:1:1:0:s) = 'K' : d s
d (0:0:1:0:0:s) = 'L' : d s
d (1:0:0:1:1:0:0:1:s) = 'M' : d s
d (1:0:0:1:1:1:1:0:s) = 'N' : d s
d (0:0:1:0:1:s) = 'O' : d s
d (1:1:1:s) = 'P' : d s
d (1:0:0:1:1:1:1:1:s) = 'Q' : d s
d (1:0:0:0:s) = 'R' : d s
d (0:0:1:1:0:s) = 'S' : d s
d (0:0:1:1:1:s) = 'T' : d s
d (1:0:0:1:1:1:0:0:s) = 'U' : d s
d (1:0:0:1:1:1:0:1:s) = 'V' : d s
d (0:0:0:0:1:0:s) = 'W' : d s
d (1:0:0:1:0:0:1:0:s) = 'X' : d s
d (1:0:0:1:0:0:1:1:s) = 'Y' : d s
d (1:0:0:1:0:0:0:0:s) = 'Z' : d s
d _ = []

main = lines <$> getContents >>= mapM_ (putStrLn . d . toBin)

博士の暗号

博 士 : ?D-C'KOPUA

ピーター : どうしたんですか、デビッド博士? わけのわからないことを叫ぶのにはもう慣れましたが、
今日は文章にすらなっていませんよ。

博 士 : ほれ。

ピーター : なんですか? この表は......ああ、予選の問題にこんなのがありました。表を使って文字を置き換え
ると文字数が減るんですよね。まさか予選と本選で同じ問題を出して手を抜こうって気じゃないでし
ょうね。

博 士 : 逆じゃよ。

ピーター : 逆? なるほど、今度は短くした文字列を元に戻そうって問題ですか。ということは「?D-C'KOPUA」の
文字を、この表を使って「文字」から「符号」に置きかえるんですね......できましたよ。

11111 00011 11101 00010 11110 01010 01110 01111 10100 00000

博 士 : うむ。次はこれじゃ。

ピーター : そうそう、こんな表もありましたね。これを逆に使うんだから「符号」から「文字」に置き換えればいい
んですね。でも、最初は「11111」ですが表にありませんよ?

博 士 : そういうときは、もっと短くするか、後ろとつなげるかしてみるのだよ。

ピ ー タ ー : じゃあ短くして......あ、 「111」ならあります。じゃあ最初は「P」ですね。そうすると残りは「11」ですが、
これはぴったり合うのがないから次の「00011」から 1 文字借りて「110」にすればいいんですね。

博 士 : そうそう。つまり「E」だね。

ピ ー タ ー : それで残るのが「0011」なので、これも次から借りて「00111」にして「T」と......。全部できました。最
後の「0000」は捨てちゃえばいいんですよね?

博 士 : そうじゃ、よろしい。次はこれじゃ。

?D-C'?-C'-LMGZN?FNJKN- WEYN?P'QMRWLPZLKKTPOVRGDI

博 士 : さらにこれじゃ。

?P'QNPY?IXX?IXXK.BI -G?R'RPP'RPOVWDMW?SWUVG'-LCMGQ

博 士 : 仕上げにこうじゃ。

?P'QMDUEQ GADKOQ ?SWUVG'-LCMG?X?IGX,PUL.?UL.VNQQI

ピ ー タ ー : しっかし面倒だなあ。博士、今度は自分でプログラムを作って下さいよ。

ということで、博士のかわりに、上の文章を置き換えるプログラムを作成してください。

Input

複数のデータセットが与えられます。各データセットとして、１つの文字列（表に含まれる文字からなる 200 文字以下の文字列）が１行に与えられます。入力の終わりまで処理してください。データセットの数は 200 を超えません。

Output

各データセットごとに、変換後の文字列を１行に出力してください。

Sample Input

?D-C'KOPUA

Output for the Sample Input

PETER POTTER


import Control.Applicative
import Control.Monad
import Data.Array.IArray
import Data.Array.IO
import Debug.Trace

main = do
  [h,w] <- map read.words <$> getLine
  unless (h == 0 && w == 0) $ do
    field <- readField (h,w)
    num <- countPD field
    print num
    main

readField :: (Int,Int) -> IO (Array (Int,Int) Char)
readField (h,w) = do
  cs <- concat <$> replicateM h getLine
  return $ listArray ((1,1),(h,w)) cs

countPD :: Array (Int,Int) Char -> IO Int
countPD arr = do
  let bs = bounds arr
      ixList = indices arr
  ioarr <- newArray bs False
  foldl (>>=) (return 0) $ map (countPDs arr ioarr) ixList

countPDs :: Array (Int, Int) Char -> IOArray (Int, Int) Bool -> (Int, Int) -> Int -> IO Int
countPDs arr ioarr ix num = do
  checkedIx <- readArray ioarr ix
  let numIx = if checkedIx then 0 else 1
  checkProperty arr ioarr ix checkedIx
--  print (ix,num + numIx)
  return $ num + numIx

printField :: IOArray (Int, Int) Bool -> IO ()
printField ioarr = do
  ((hmin,wmin),(hmax,wmax)) <- getBounds ioarr
  forM_ [hmin..hmax] $ \i -> do
    forM_ [wmin..wmax] $ \j -> do
      b <- readArray ioarr (i,j)
      if b then putStr "T" else putStr "F"
    putStrLn ""

checkProperty :: Array (Int, Int) Char -> IOArray (Int, Int) Bool -> (Int, Int) -> Bool -> IO ()
checkProperty arr ioarr ix checkedIx = do
  if checkedIx
     then return ()
     else do
       let (h,w) = ix
       writeArray ioarr ix True
       updateField arr ioarr ix

updateField :: Array (Int, Int) Char -> IOArray (Int, Int) Bool -> (Int, Int) -> IO ()
updateField arr ioarr (h,w) = do --traceShow (h,w) $ do
  rightUpdate arr ioarr (h,w)
  underUpdate arr ioarr (h,w)

rightUpdate :: Array (Int, Int) Char -> IOArray (Int, Int) Bool -> (Int, Int) -> IO ()
rightUpdate arr ioarr (h,w) = do --trace ("right" ++ show (h,w)) $ do
  let ((hmin,wmin),(hmax,wmax)) = bounds arr
  case (hmax == h, wmax == w) of
       (_, True) -> return ()
       (True, False) -> bottomAction
       (False, False) -> normalAction
  where
    updateAction = do
      let originProp = arr ! (h,w)
          rightProp = arr ! (h,w+1)
      if originProp == rightProp
         then writeArray ioarr (h,w+1) True >> return True
         else return False
    bottomAction = do
      continue <- updateAction
      if continue then rightUpdate arr ioarr (h,w+1)
                  else return ()
    normalAction = do
      continue <- updateAction
      if continue then rightUpdate arr ioarr (h,w+1) >> underUpdate arr ioarr (h,w+1)
                  else return ()

leftUpdate arr ioarr (h,w) = do --trace ("left " ++ show (h,w)) $ do
  let ((hmin,wmin),(hmax,wmax)) = bounds arr
  case (hmax == h, wmin == w) of
       (_, True) -> return ()
       (True, False) -> bottomAction
       (False, False) -> normalAction
  where
    updateAction = do
      checked <- readArray ioarr (h,w-1)
      if checked then return False
                 else do
                    let originProp = arr ! (h,w)
                        leftProp = arr ! (h,w-1)
                    if originProp == leftProp
                       then writeArray ioarr (h,w-1) True >> return True
                       else return False
    bottomAction = do
      continue <- updateAction
      if continue then leftUpdate arr ioarr (h,w-1)
                  else return ()
    normalAction = do
      continue <- updateAction
      if continue then leftUpdate arr ioarr (h,w-1) >> underUpdate arr ioarr (h,w-1)
                  else return ()

underUpdate arr ioarr (h,w) = do --trace ("under" ++ show (h,w)) $ do
  let ((hmin,wmin),(hmax,wmax)) = bounds arr
  case (hmax == h, wmax == w, wmin == w) of
       (True, _, _) -> return ()
       (False, True, False) -> rightEdgeAction
       (False, False, True) -> leftEdgeAction
       (False, False, False) -> normalAction
  where
    updateAction = do
      let originProp = arr ! (h,w)
          rightProp = arr ! (h+1,w)
      if originProp == rightProp
         then writeArray ioarr (h+1,w) True >> return True
         else return False
    rightEdgeAction = do
      continue <- updateAction
      if continue then underUpdate arr ioarr (h+1,w) >> leftUpdate arr ioarr (h+1,w)
                  else return ()
    leftEdgeAction = do
      continue <- updateAction
      if continue then underUpdate arr ioarr (h+1,w) >> rightUpdate arr ioarr (h+1,w)
                  else return ()
    normalAction = do
      continue <- updateAction
      if continue then rightUpdate arr ioarr ((h+1,w)) >> leftUpdate arr ioarr (h+1,w) >> underUpdate arr ioarr ((h+1,w))
                  else return ()

Property Distribution

タナカ氏が HW アールの果樹園を残して亡くなりました。果樹園は東西南北方向に H × W の区画に分けられ、区画ごとにリンゴ、カキ、ミカンが植えられています。タナカ氏はこんな遺言を残していました。

果樹園は区画単位でできるだけ多くの血縁者に分けること。ただし、ある区画の東西南北どれかの方向にとなりあう区画に同じ種類の果物が植えられていた場合は、区画の境界が分からないのでそれらは 1 つの大きな区画として扱うこと。

例えば次のような 3 × 10 の区画であれば ('リ'はリンゴ、'カ'はカキ、'ミ'はミカンを表す)

同じ樹がある区画の間の境界を消すと次のようになり、

結局 10 個の区画、つまり 10 人で分けられることになります。

雪が降って区画の境界が見えなくなる前に分配を終えなくてはなりません。あなたの仕事は果樹園の地図をもとに分配する区画の数を決めることです。

果樹園の地図を読み込み、分配を受けられる血縁者の人数を出力するプログラムを作成してください。

Input

複数のデータセットが与えられます。各データセットは空白で区切られた H, W (H, W ≤ 100) を含む行から始まり、続いて H × W の文字からなる H 行の文字列が与えられます。この文字列には、リンゴを表す '@'、カキを表す '#'、ミカンを表す '*'、の 3 文字しか現れません。

入力はゼロが２つの行で終わります。データセットの数は 20 を超えません。

Output

各データセットごとに、分配を受ける人数を１行に出力してください。

Sample Input

10 10
####*****@
@#@@@@#*#*
@##***@@@*
#****#*@**
##@*#@@*##
*@@@@*@@@#
***#@*@##*
*@@@*@@##@
*@*#*@##**
@****#@@#@
0 0

Output for the Sample Input

33


import Control.Monad
import Data.List

getNums = getLine >>= return . map read . words

solve n ps js = f (n*m) n m (reverse $ sort js)
 where
  m = sum ps
  f a _ _ [] = a
  f a n m (j:js)
   | a > a' = a
   | otherwise = f a' n' m' js
   where
    n' = n-1
    m' = m+j
    a' = n'*m'

main = do
 (n:_) <- getNums
 when (n /= 0) $ do
  ps <- getNums
  js <- getNums
  print $ solve n ps js
  main

パイプつなぎ職人の給料

ぼくはパイプつなぎ職人です。パイプをつなぐジョイントとパイプさえもらえれば、どんなパイプだってつないでみせます。ぼくは毎日、親方からパイプとジョイントを渡されて、それをつないで親方に渡します。でも、パイプの数が多すぎるときは、１日でそれを全部つなげることはできません。そんなときでも親方はにっこり笑って、ぼくに給料を渡してくれます。

ところで、あるとき変なことに気がつきました。全部のパイプをつなげられたときより、つなげられなかったときの方が給料が多いことがしょっちゅうあるんです。あんまり変なので、ある日、親方が来たときに、給料の計算方法が書いてあるメモをこっそり見ちゃいました。そしたら、なんと

"給料は「パイプの本数×パイプの長さの総和」で支払う。ただし、ジョイントでつなげて、ひとつながりになったものは、それを１本のパイプとみなす。"

って書いてありました。これで全部つなげた方が給料が安くなることがある理由がわかりました。たとえば下図のように、長さ 1 のパイプ 3 本と長さ 2 のジョイント 2 本を全部つなげると長さ 1+2+1+2+1 = 7 のパイプが 1 本できるので、1 × (7) = 7 です。でも、ジョイントを一つだけ使って長さ 1+2+1 = 4のパイプと長さ 1 のパイプの 2 本にすると2 × (4+1) = 10なので、全部つなげるよりいっぱい給料がもらえます。

親方がなんでこんな方法で給料を決めてるかわからないけど、これでぼくもどうすればもらえる給料を多くできるかわかりました！

それでは、パイプの本数が与えられたとき、もらえる給料の最大の金額を計算するプログラムを作成してください。

入力

入力は複数のデータセットからなる。入力の終わりはゼロ１つの行で示される。各データセットは以下の形式で与えられる。

n
p1 ... pn
j1 ... jn-1

１行目にパイプの本数 n (2 ≤ n ≤ 65000) が与えられる。２行目は１つの空白で区切られた n 個の整数からなる。pi (1 ≤ pi ≤ 1000) はi番目のパイプの長さを示す。３行目は１つの空白で区切られた n-1 個の整数からなる。ji (1 ≤ ji ≤ 1000) は i 番目のジョイントの長さを示す。

i番目のジョイントは、i 番目と i+1 番目のパイプだけをつなげることができる。つなげたパイプの長さは、pi + ji + pi+1 になる。

データセットの数は 100 を超えない。

出力

各データセットごとに、得られる給料の最大の金額を1行に出力する。入力として与えられるデータセットでは、出力される値は必ず３２ビット符号無し整数の範囲に収まるものとする。

入力例1

3
1 1 1
3 3
4
3 3 3 3
1 1 1
5
1 2 3 4 5
4 3 2 1
0

出力例

12
48
76


import Text.Printf

turn:: (Int,Int) -> (Int,Int)
turn (a,b)
        | a >  b = (a+b,0)
        | a == b = (a,b)
        | a <  b = (0,a+b)

acm:: [(Int,Int)] -> (Int,Int)
acm [] = (0,0)
acm ((a,b):xs) =
        let (c,d) = acm xs
        in
                (a+c,b+d)

play:: [[Int]] -> [(Int,Int)]
play ([0]:ns) = []
play (n:ns) =
    let i = take (n!!0) ns
        o = acm $ map turn $ map (\(x0:x1:xs) -> (x0,x1)) i
        os= play $ drop (n!!0) ns
    in
        (o:os)

main = do
    c <- getContents
    let t0= map words $ lines c
        t1= map (map read) t0 :: [[Int]]
        o = play t1
    mapM_ (\(a,b)-> printf "%d %d\n" a b) o

A と B の 2 人のプレーヤーが， 0 から 9 までの数字が書かれたカードを使ってゲームを行う．最初に， 2 人は与えられた n 枚ずつのカードを，裏向きにして横一列に並べる．その後， 2 人は各自の左から 1 枚ずつカードを表向きにしていき，書かれた数字が大きい方のカードの持ち主が，その 2 枚のカードを取る．このとき，その 2 枚のカードに書かれた数字の合計が，カードを取ったプレーヤーの得点となるものとする．ただし，開いた 2 枚のカードに同じ数字が書かれているときには，引き分けとし，各プレーヤーが自分のカードを 1 枚ずつ取るものとする．

例えば， A，B の持ち札が，以下の入力例 1 から 3 のように並べられている場合を考えよう．ただし，入力ファイルは n + 1 行からなり， 1 行目には各プレーヤのカード枚数 n が書かれており， i + 1 行目（i = 1，2，... ，n）には A の左から i 枚目のカードの数字と B の左から i 枚目の カードの数字が，空白を区切り文字としてこの順で書かれている．すなわち，入力ファイルの 2 行目以降は，左側の列が A のカードの並びを，右側の列が B のカードの並びを，それぞれ表している．このとき，ゲーム終了後の A と B の得点は，それぞれ，対応する出力例に示したものとなる．

　入力ファイルに対応するゲームが終了したときの A の得点と B の得点を，この順に空白を区切り文字として 1 行に出力するプログラムを作成しなさい．ただし， n ≤ 10000 とする．

入力例１

入力例２

入力例３

3

3

3

9 1

9 1

9 1

5 4

5 4

5 5

0 8

1 0

1 8

出力例１

出力例２

出力例３

19 8

20 0

15 14

入力

入力は複数のデータセットからなる．n が 0 のとき入力が終了する．データセットの数は 5 を超えない．

出力

データセットごとに、A の得点と B の得点を１行に出力する．

入力例

3
9 1
5 4
0 8
3
9 1
5 4
1 0
3
9 1
5 5
1 8
0

出力例

19 8
20 0
15 14

各データセットの出力の後（Bの得点の後）に改行を入れること。

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


import Control.Applicative ((<$>))
import Control.Monad (replicateM, unless)
import Data.Map (Map)
import qualified Data.Map as M

main :: IO ()
main = do
  n <- readLn
  unless (n == 0) $ do
    tbl <- M.fromList <$> map f <$> replicateM n (words <$> getLine)
    m <- readLn
    solve tbl <$> replicateM m (head <$> getLine) >>= putStrLn
    main
  where f [a, b] = (head a, head b)

solve :: Map Char Char -> String -> String
solve tbl = map f
  where f c = maybe c id $ M.lookup c tbl

与えられた変換表にもとづき，データを変換するプログラムを作成しなさい．

データに使われている文字は英字か数字で，英字は大文字と小文字を区別する．変換表に現れる文字の順序に規則性はない．

変換表は空白をはさんで前と後ろの 2 つの文字がある(文字列ではない)．変換方法は，変換表のある行の前の文字がデータに現れたら，そのたびにその文字を後ろの文字に変換し出力する．変換は 1 度だけで，変換した文字がまた変換対象の文字になっても変換しない．変換表に現れない文字は変換せず，そのまま出力する．

入力ファイルには，変換表（最初の n + 1 行）に続き変換するデータ（n + 2 行目以降）が書いてある． 1 行目に変換表の行数 n，続く n 行の各行は，空白をはさんで 2 つの文字，さらに続けて， n + 2 行目に変換するデータの行数 m，続く m 行の各行は 1 文字である． m ≤ 105 とする．出力は，出力例のように途中に空白や改行は入れず 1 行とせよ．

入力例

3

A a

0 5

5 4

10

A

B

C

0

1

4

5

a

b

A

出力例

aBC5144aba

入力

入力は複数のデータセットからなる．n が 0 のとき入力が終了する．データセットの数は 5 を超えない．

出力

データセットごとに、変換後の文字列を１行に出力する．

入力例

3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0

出力例

aBC5144aba
aBC5144aba

各データセットの出力（変換後の文字列）の後に改行を入れること．

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


{-#LANGUAGE BangPatterns#-}
module Main where

import Data.Functor
import Control.Monad

main::IO ()
main=do
  n<-read <$> getLine::IO Int
  when (n/=0) $
    do
      str <- getLine
      let out=times (toStr . split) str n
      putStrLn out
      main

toStr::[(Int,Char)]->String
toStr list=concatMap (\(n,c)->show n ++ [c])list

split::Eq a=>[a]->[(Int,a)]
split list=reverse $ split' 0 [] list

split'::Eq a=>Int->[(Int,a)]->[a]->[(Int,a)]
split' _ result []=result
split' !n result (x:y:ys)
  |x==y =split' (n+1) result (y:ys)
  |otherwise =split' 0 ((n+1,x):result) (y:ys)
split' !n result [x]=split' 0 ((n+1,x):result) []

times::(a->a)->a->Int->a
times _ x 0=x
times f x n=times f (f x) (n-1)

0 から 9 までの数字だけで構成された文字列が与えられたとき,その文字列から次の規則に従って新しい文字列を作る操作を考える.与えられた文字列を左端から1文字ずつ順に読んで行き,同じ数字 a が r 個続いていた場合,個数 r と数字a を空白で区切らずにこの順で書き出す.与えられた文字列の右端まで読み,最後の書き出しが終わったところまでを途中何回書き出しがあったとしても全部まとめて操作1回とカウントする.2回目以降の操作は前回の操作により書き出された文字列を与えられた文字列として同様の操作を実施する.例えば “122244” という文字列が与えられた場合には左端から順に1個の1, 3個の2,2個の4なのでこの操作1回で得られる文字列は “113224” であり,“44444444444” (11 個の4)の場合には得られる文字列は “114” となる.

100 文字以下の与えられた文字列に上の操作を n 回実施した文字列を出力するプログラムを作成せよ.ただし, n ≤ 20 とする.

入力データ は 2 行からなり,1 行目に操作回数 n, 2 行目に最初の文字列が書かれている.

入力例

5

11

出力例

13112221

入力

入力は複数のデータセットからなる．n が 0 のとき入力が終了する．データセットの数は 5 を超えない．

出力

データセットごとに、指定された回数の操作を施した文字列 を１行に出力する．

入力例

5
11
5
11
0

出力例

13112221
13112221

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


import Data.List (sort,tails)
import System.IO (isEOF)

main = do
    quit <- isEOF
    if quit then return () else do
        s1 <- getLine
        s2 <- getLine
        print $ solve s1 s2
        main

solve :: String -> String -> Int
solve s1 s2 = solve' (sort $ tails s1) (sort $ tails s2) 0
    where
    solve' [] _ n = n
    solve' _ [] n = n
    solve' (u:us) (v:vs) n
        | u < v = solve' us (v:vs) (max n (matchN u v))
        | u > v = solve' (u:us) vs (max n (matchN u v))
        | u == v = solve' us vs (max n (matchN u v))

    matchN "" _ = 0
    matchN _ "" = 0
    matchN (c:cs) (d:ds)
        | c == d = 1 + matchN cs ds
        | c /= d = 0

共通部分文字列

問題

2 個の文字列が与えられたとき, 両方の文字列に含まれる文字列のうち最も長いものを探し, その長さを答えるプログラムを作成せよ.

ここで, 文字列 s が文字列 t に含まれるとは, t の中に s が連続して現れることをいう. 空文字列, すなわち長さ 0 の文字列は, どんな文字列にも含まれる. 例えば, 文字列 ABRACADABRA には次の文字列が含まれる: ABRA, RAC, D, ACADABRA, ABRACADABRA,空文字列など. 一方, 文字列 ABRACADABRA には次の文字列は含まれない: ABRC, RAA,BA, K など.

例

例 1: 文字列として ABRACADABRA と ECADADABRBCRDARA が与えられた場合, 両方に含まれる文字列には CA や CADA や ADABR や空文字列などがある. そのうち最も長いのは ADABR であり, その長さは 5 である. 2 個の文字列の中に含まれる ADABR
の位置を以下に示す.

ABRACADABRA

ECADADABRBCRDARA

例 2: 文字列として UPWJCIRUCAXIIRGL と SBQNYBSBZDFNEV が与えられた場合, 両方に含まれる文字列は空文字列のみであり, その長さは 0 である.

入力

入力は複数のデータセットからなる．各データセットは以下の形式で与えられる．

入力は 2 行からなり, 1 行目に 1 個目の文字列が, 2 行目に 2 個目の文字列が与えられる. 文字列は英大文字からなり, 各々の文字列の長さは 1 以上 4000 以下である.

採点用データのうち, 配点の 30% 分については, 各々の文字列の長さは 1 以上 50以下である.

入力の終わりは EOF で示される. データセットの数は 10 を超えない．

出力

データセットごとに与えられた 2 個の文字列の両方に含まれる文字列のうち最も長いものの長さを 1 行に出力する.

入出力例

入力例

ABRACADABRA
ECADADABRBCRDARA
UPWJCIRUCAXIIRGL
SBQNYBSBZDFNEV

出力例

5
0

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Functor
import Data.Function
import Data.Monoid
import Data.Maybe
import Data.List
import qualified Data.Foldable as Foldable
import qualified Data.Set as Set
import Data.List.Split
import Data.Bits
import Data.Char
import Data.Ix
import Data.Ratio
import Data.Ord
import Data.Tuple
import Data.Array
--import Data.Array.Unboxed
import Data.Array.MArray
import Data.Array.IO
import Data.Array.ST
import Data.IORef
import Data.STRef
-- import System.IO.Unsafe

readInt = read :: String -> Int
readDouble = read :: String -> Double
getInt = readLn :: IO Int
getInts = map readInt . words <$> getLine
getDouble = readLn :: IO Double
sjoin :: (Show a) => [a] -> String
sjoin = unwords . map show
cond :: a -> a -> Bool -> a
cond t f c = if c then t else f
apply2 :: (a -> a -> b) -> [a] -> b
apply2 f [x,y] = f x y
apply3 :: (a -> a -> a -> b) -> [a] -> b
apply3 f [x,y,z] = f x y z
apply4 :: (a -> a -> a -> a -> b) -> [a] -> b
apply4 f [x,y,z,w] = f x y z w
fnBin :: (b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d
fnBin op f g x = op (f x) $ g x
fnTuple :: (a -> b, a -> c) -> a -> (b, c)
fnTuple (f,g) a = (f a, g a)
replace :: (Eq a) => a -> a -> [a] -> [a]
replace x y = map (\z -> if z==x then y else z)
modifyArray :: (Ix i, MArray a e m) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = readArray arr ix >>= writeArray arr ix . f
-- end of templete

charMap 'J' = 0
charMap 'O' = 1
charMap 'I' = 2

main = do
    [m, n] <- getInts
    k <- getInt
    arr <- newArray ((0,0,0),(2,m,n)) 0 :: IO (IOUArray (Int,Int,Int) Int)
    forM_ [1..m] $ \y -> do
        s <- getLine
        forM_ (zip [1..n] s) $ \(x, c) -> do
            writeArray arr (charMap c,y,x) 1
    forM_ [(t,y,x) | t <- [0..2], y <- [1..m], x <- [1..n]] $ \(t,y,x) ->  (-) <$> ((+) <$> readArray arr (t,y,x) <*> ((+) <$> readArray arr (t,y-1,x) <*> readArray arr (t,y,x-1))) <*> readArray arr (t,y-1,x-1) >>= writeArray arr (t,y,x)
    replicateM_ k $ do
        [a,b,c,d] <- getInts
        sequence [(-) <$> ((+) <$> readArray arr (i,c,d) <*> readArray arr (i, a-1, b-1)) <*> ((+) <$> readArray arr (i,c,b-1) <*> readArray arr (i, a-1, d)) | i <- [0..2]] >>= putStrLn . sjoin
    return ()

惑星探査(Planetary Exploration)

あなたを乗せた超時空移民船は長旅の末，ついに居住可能と思われる惑星を発見した．JOI 星と名付けられたその惑星は，その名の通り「ジャングル(Jungle)」，「海(Ocean)」，「氷(Ice)」の3 種類の地形が入り組んだ過酷な惑星である．簡単な調査により，居住予定地近辺の地図が作成された．居住予定地は南北M km, 東西N km の長方形の形をしており， 1 km 四方の正方形の区画に分けられている．区画は全部でMN 個あり，北からp 行目，西からq 列目の区画を(p, q) で表す．北西の角の区画が(1, 1) であり，南東の角の区画が(M, N) である．各区画の地形は，「ジャングル」，「海」，「氷」のいずれかであり，「ジャングル」はJ, 「海」はO, 「氷」はI の英字1 文字で表される.

さて，詳細な移住計画を立てるにあたり， K 箇所の長方形領域内に「ジャングル」，「海」，「氷」がそれぞれ何区画含まれるかを調べることにした．

課題

居住予定地の情報と，調査対象となる領域の情報が与えられたとき，それぞれの領域について， 「ジャングル」，「海」，「氷」が何区画含まれているかを求めるプログラムを作成せよ．

制限

1 ≤ M ≤ 1000    居住予定地の南北の長さ(km)

1 ≤ N ≤ 1000    居住予定地の東西の長さ(km)

1 ≤ K ≤ 100000    調査対象となる領域の個数

入力

標準入力から以下の入力を読み込め．

1 行目には整数M, N が空白を区切りとして書かれており，居住予定地が南北にM km ，東西にN km の広さであることを表す．

2 行目には整数K が書かれており，調査対象となる領域の個数を表す．

続くM 行には居住予定地の情報が書かれている．i + 2 行目(1 ≤ i ≤ M) には，居住予定地の北からi行目に位置するN 区画の情報を表すJ，O，I からなるN 文字の文字列が書かれている．

続くK 行には調査対象となる領域が書かれている．j + M + 2 行目(1 ≤ j ≤ K) には， j 番目の領域を表す正整数aj, bj, cj, dj が空白を区切りとして書かれている．(aj, bj) は調査領域の北西の角の区画を，(cj, dj) は調査領域の南東の角の区画を表す．ただし，aj, bj, cj, dj は，1 ≤ aj ≤ cj ≤ M, 1 ≤ bj ≤ dj ≤ Nを満たす．

出力

標準出力に調査の結果を表すK 行を出力せよ．出力のj 行目には， j 番目の調査領域に含まれる「ジャングル」(J) の区画数，「海」(O) の区画数，「氷」(I) の区画数を表す3 つの整数を，この順に空白を区切りとして書け．

採点基準

採点用データのうち，配点の30%分については，M ≤ 50 かつK ≤ 100 を満たす．配点の50%分については，M ≤ 50 を満たす．

入出力の例

入力例

4 7
4
JIOJOIJ
IOJOIJO
JOIJOOI
OOJJIJO
3 5 4 7
2 2 3 6
2 2 2 2
1 1 4 7

出力例

1 3 2
3 5 2
0 1 0
10 11 7

この入力例では， 2 番目の領域は上図のように「ジャングル」を3 区画，「海」を5 区画，「氷」を2 区画含む．

問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


import Control.Applicative ((<$>))
import Control.Monad (replicateM, unless)
import Data.List (foldl')
import Data.Vector.Unboxed (Vector, (!), (//))
import qualified Data.Vector.Unboxed as V

main :: IO ()
main = do
  n <- readLn
  unless (n == 0) $ do
    solve n <$> replicateM n (f <$> words <$> getLine) >>= putStrLn
    main
  where f (s:_:ls) = (s, map read ls)

solve :: Int -> [(String, [Int])] -> String
solve n xs = f . minimum . map (\(s, ts) -> (count ts, s)) $ xs
  where ph = foldl' (\h x -> V.accum (+) h [(x,1)]) (V.replicate 31 0) (concatMap snd xs) :: Vector Int
        count = sum . map (\t -> n + 1 - ph ! t)
        f (t, s) = unwords [show t, s]

Problem A: Popularity Estimation

あなたはとあるアニメーション制作会社の企画部長である。昨今のアニメーション制作会社が制作するものは、アニメーションそのものにとどまらない。関連商品、例えば登場キャラクターのフィギュアやキャラクターソングCDなども、重要な収益源なのである。この収益をどれだけ伸ばせるかは、ひとえに企画部長のあなたにかかっているのであった。

当たり前のことだが、こういった関連商品は闇雲に発売すればいいというものではない。商品の開発には多くの時間と予算が必要なためだ。アニメの登場キャラクターのフィギュアを発売するにしても、多くの売上が見込まれる、人気があるキャラクターのものに限らなければならない。

キャラクターの人気度を測る手段の一つが、人気投票である。あなたも今までいくつかの人気投票を企画してきたが、どうやら視聴者はこの企画に不満を抱きつつあるようだ。人気度を測る他の手法の確立が急務である。

そこであなたは、ひとつの仮説を立てた。あるキャラクターの人気度は、そのアニメ本編中における登場時間の総和に比例する、というものだ。あなたはこの仮説を検証するため、それぞれのキャラクターの登場時間を集計するプログラムを書くことにした。

Input

入力は複数のケースからなる。
各ケースは以下のフォーマットで与えられる。

n
name0 m0 d0,0 ... d0,m0-1
name1 m1 d1,0 ... d1,m1-1
.
.
.
namen-1 mn-1 dn-1,0 ... dn-1,mn-1-1

n はキャラクターの人数を表す。

namei はキャラクターの名前を表す。

mi はキャラクターが映っていた時刻の種類を表す。

mi の後にはmi 個の整数di,j が与えられる。

di,jはキャラクターが映っていた時刻を表す。

入力の終わりはn=0 からなる行によって与えられる

ある時刻に1人のキャラクターのみが画面に映っていた場合、そのキャラクターはnポイントを得ることが出来る。

同時刻に映るキャラクターが1人増える毎に、その時刻に映っていたキャラクターが得られるポイントは1減る。

n人のキャラクターが同時刻に映っていた場合、n人の人それぞれに1ポイントが加算される。

入力は以下の制約を満たす。

2 ≤ n ≤ 20

0 ≤ mi ≤ 30

0 ≤ di,j < 30

i 番目のキャラクターについてdi,j はすべて異なる。

namei はアルファベットの大文字または小文字のみを含み、長さは10以下である。

Output

最小のポイントを持つキャラクターのポイントとその名前を1つの空白で区切って出力せよ。

最小のポイントを持つキャラクターが複数いる場合は名前が辞書順で最小の人を選ぶこと。

Sample input

4
akzakr 2 1 8
fnmyi 5 2 3 4 6 9
tsnukk 5 2 3 4 7 9
yskwcnt 6 3 4 7 8 9 10
4
akzakr 1 2
fnmyi 3 10 11 12
tsnukk 2 1 8
yskwcnt 2 1 8
5
knmmdk 2 13 19
akmhmr 4 13 15 19 22
mksyk 6 3 7 12 13 15 19
skrkyk 3 1 4 8
tmemm 3 1 17 24
5
knmmdk 5 5 6 16 18 26
akmhmr 9 3 4 7 11 14 15 17 18 20
mksyk 5 6 13 25 27 28
skrkyk 4 3 16 23 24
tmemm 3 6 12 20
14
hrkamm 6 4 6 8 10 20 22
mkhsi 6 1 10 12 15 22 27
hbkgnh 2 4 9
chyksrg 8 3 4 12 15 16 20 25 28
mktkkc 6 0 1 8 15 17 20
tknsj 6 6 8 18 19 25 26
yyitktk 3 3 12 18
ykhhgwr 5 3 9 10 11 24
amftm 7 2 6 8 12 13 14 17
mmftm 4 6 12 16 18
rtkakzk 3 14 15 21
azsmur 7 1 2 4 12 15 18 20
iormns 2 4 20
ktrotns 6 7 12 14 17 20 25
14
hrkamm 2 4 21
mkhsi 6 2 3 8 11 18 20
hbkgnh 4 4 16 28 29
chyksrg 5 0 3 9 17 22
mktkkc 2 7 18
tknsj 3 3 9 23
yyitktk 3 10 13 25
ykhhgwr 2 18 26
amftm 3 13 18 22
mmftm 4 1 20 24 27
rtkakzk 2 1 10
azsmur 5 2 5 10 14 17
iormns 3 9 15 16
ktrotns 5 7 12 16 17 20
0

Sample output

7 akzakr
4 akzakr
6 knmmdk
12 tmemm
19 iormns
24 mktkkc

The University of Aizu Programming Contest 2011 Summer

原案: Tomoya Sakai

問題文: Takashi Tayama


import Control.Applicative ((<$>))
import Control.Monad (unless)

main :: IO ()
main = do
  [a, b, c] <- map read <$> words <$> getLine
  unless (a == 0 && b == 0 && c == 0) $ do
    putStrLn $ solve a b c
    main

solve :: Int -> Int -> Int -> String
solve a b c | d < 0 = "Impossible"
            | d /= srd ^ 2 = "Impossible"
            | otherwise = unwords . map show $ if p' > r' then [p', q', r', s']
                                               else if p' < r' then [r', s', p', q']
                                                    else if q' > s' then [p', q', r', s']
                                                         else [r', s', p', q']
  where d = b ^ 2 - 4 * a * c
        srd = floor . sqrt . fromIntegral $ d
        (p', q') = let g = gcd (2*a) (b-srd) in ((2*a) `div` g, (b-srd) `div` g)
        (r', s') = let g = gcd (2*a) (b+srd) in ((2*a) `div` g, (b+srd) `div` g)

Factorization of Quadratic Formula

As the first step in algebra, students learn quadratic formulas and
their factorization. Often, the factorization is a severe burden
for them. A large number of students cannot master the factorization;
such students cannot be aware of the elegance of advanced algebra.
It might be the case that the factorization increases the number of people
who hate mathematics.

Your job here is to write a program which helps students of
an algebra course. Given a quadratic formula, your program should report
how the formula can be factorized into two linear formulas.
All coefficients of quadratic formulas and those of resultant
linear formulas are integers in this problem.

The coefficients a, b and c of a quadratic formula
ax2 + bx + c are given.
The values of a, b and c are integers,
and their absolute values do not exceed 10000.
From these values, your program is requested to find four integers
p, q, r and s, such that
ax2 + bx + c =
(px + q)(rx + s).

Since we are considering integer coefficients only, it is not
always possible to factorize a quadratic formula into linear formulas.
If the factorization of the given formula is impossible,
your program should report that fact.

Input

The input is a sequence of lines, each representing
a quadratic formula.
An input line is given in the following format.

a b c

Each of a, b and c is an integer.
They satisfy the following inequalities.

0 < a <= 10000

-10000 <= b <= 10000

-10000 <= c <= 10000

The greatest common divisor of a, b and c is 1.
That is, there is no integer k, greater than 1,
such that all of a, b and c are divisible by k.

The end of input is indicated by a line consisting of three 0's.

Output

For each input line, your program should output the four integers
p, q, r and s in a line, if they exist.
These integers should be output in this order, separated by
one or more white spaces.
If the factorization is impossible, your program should output a line
which contains the string "Impossible" only.

The following relations should hold between the values
of the four coefficients.

p > 0

r > 0

(p > r) or (p = r and q >= s)

These relations, together with the fact that the greatest common
divisor of a, b and c is 1,
assure the uniqueness of the solution.
If you find a way to factorize the formula, it is not necessary
to seek another way to factorize it.

Sample Input

2 5 2
1 1 1
10 -7 0
1 0 -3
0 0 0

Output for the Sample Input

2 1 1 2
Impossible
10 -7 1 0
Impossible


{-
URL: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1130&lang=jp
?????????: Red and Black
?????°
19:08:06 ??¶?´???????????????§Haskell??§??????????????????
19:17:53 ??¨??????????????????????????¨?????´??°??????bar???????£?????????????
19:32:19 ????????????
19:34:02 ??????fmap???????????????
-}
import Control.Monad
import Control.Applicative
import Data.List

main :: IO ()
main = do
 [w,h] <- (map read . words) `fmap` getLine
 when ((w,h) /= (0,0)) $ do
  arr <- replicateM h getLine
  print $ foo arr
  main

type Stat = (Integer, [[Char]])

foo :: [[Char]] -> Integer
foo arr = fst $ repetitive bar (1,arr)

repetitive :: Eq t => (t -> t) -> t -> t --??????????????????????????§?????¨????????????????±???????
repetitive f s = if f s == s then s else repetitive f (f s)

bar :: Stat -> Stat -- "@"????????????"."???"@"?????????
bar = f . f
 where f = fmap transpose . bar1 ".@" . bar1 "@."

bar1 :: String -> Stat -> Stat -- replace all `bef` with "@@", while counting the num
bar1 bef (num, dat) = (num + sum(map fst d'), map snd d')
 where
  d' = map f dat
  f :: String -> (Integer,String)
  f str
   | null str = (0,"")
   | bef `isPrefixOf` str = count $ ("@@" ++) `fmap` f(drop 2 str)
   | otherwise = (head str :) `fmap` f (tail str)

count :: (Integer,a) -> (Integer,a)
count(a,b)=(a+1,b)

Problem B: Red and Black

There is a rectangular room, covered with square tiles. Each tile is
colored either red or black. A man is standing on a black tile.
From a tile, he can move to one of four adjacent tiles. But he can't
move on red tiles, he can move only on black tiles.

Write a program to count the number of black tiles which he can reach
by repeating the moves described above.

Input

The input consists of multiple data sets.
A data set starts with a line containing two positive integers W and H;
W and H are the numbers of tiles in the x-
and y- directions, respectively. W and H are
not more than 20.

There are H more lines in the data set, each of which
includes W characters. Each character represents the color of a
tile as follows.

'.' - a black tile

'#' - a red tile

'@' - a man on a black tile(appears exactly once in a data set)

The end of the input is indicated by a line consisting of two zeros.

Output

For each data set, your program
should output a line which contains the number of
tiles he can reach from the initial tile (including itself).

Sample Input

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0

Output for the Sample Input

45
59
6
13


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

data Point = Point (Double, Double) deriving (Show)
add (Point (x1, y1)) (Point (x2, y2)) = Point (x1 + x2, y1 + y2)
sub (Point (x1, y1)) (Point (x2, y2)) = Point (x1 - x2, y1 - y2)
mul (Point (x, y)) s = Point (x * s, y * s)
det (Point (x1, y1)) (Point (x2, y2)) = x1 * y2 - y1 * x2
nrm (Point (x, y)) = Point (x / n, y / n) where n = sqrt $ (x * x + y * y)
dist (Point (x1, y1)) (Point (x2, y2)) = sqrt (dx * dx + dy * dy) where
    dx = x1 - x2
    dy = y1 - y2

getX (Point (x, _)) = x
getY (Point (_, y)) = y

parsePoint :: String -> Point
parsePoint str =
    let [x, y] = map read $ words str
    in Point (x, y)

calcCenter :: Point -> Point -> (Point, Point)
calcCenter a b =
    let m = (a `add` b) `mul` 0.5
        d = sqrt (1.0 - (dist a m))
        e = a `sub` b
        n = nrm $ Point (negate $ getY e, getX e)
        c1 = m `add` (n `mul` d)
        c2 = m `sub` (n `mul` d)
    in (c1, c2)

solve' :: [Point] -> Int
solve' pts =
    let cs = [ calcCenter a b | a <- pts, b <- pts ]
        inside p q = (dist p q) <= 1.0
        countIn c = length $ filter (\p -> inside c p) pts
        m1 = maximum $ map (countIn . fst) cs
        m2 = maximum $ map (countIn . snd) cs
    in (max m1 m2)

solve :: [String] -> [Int]
solve []   = []
solve cont =
    let n           = read (head cont) :: Int
        (crds, rst) = splitAt n (tail cont)
        pts         = map parsePoint crds
    in if n == 0 then []
                 else (solve' pts) : solve rst

main :: IO ()
main = do
    contents <- getContents
    mapM_ print $ solve $ lines contents

Problem D: Circle and Points

You are given N points in the xy-plane. You have a
circle of radius one and move it on the xy-plane, so as to
enclose as many of the points as possible. Find how many points can be
simultaneously enclosed at the maximum. A point is considered
enclosed by a circle when it is inside or on the circle.

Fig 1. Circle and Points

Input

The input consists of a series of data sets, followed by a single line
only containing a single character '0', which indicates the end of the
input. Each data set begins with a line containing an integer N,
which indicates the number of points in the data set. It is
followed by N lines describing the coordinates of the
points. Each of the N lines has two decimal fractions X
and Y, describing the x- and y-coordinates of a
point, respectively. They are given with five digits after the decimal
point.

You may assume 1 <= N <= 300, 0.0 <= X <= 10.0, and 0.0
<= Y <= 10.0. No two points are closer than 0.0001. No two
points in a data set are approximately at a distance of 2.0. More
precisely, for any two points in a data set, the distance d
between the two never satisfies 1.9999 <= d <= 2.0001. Finally,
no three points in a data set are simultaneously very close to a
single circle of radius one. More precisely,
let P1, P2, and P3 be any three points in a
data set, and d1, d2, and d3
the distances from an arbitrarily selected point in the xy-plane to each of them
respectively. Then it never simultaneously holds that 0.9999 <=
di <= 1.0001 (i = 1, 2, 3).

Output

For each data set, print a single line containing the maximum number
of points in the data set that can be simultaneously enclosed by a
circle of radius one. No other characters including leading and
trailing spaces should be printed.

Sample Input

3
6.47634 7.69628
5.16828 4.79915
6.69533 6.20378
6
7.15296 4.08328
6.50827 2.69466
5.91219 3.86661
5.29853 4.16097
6.10838 3.46039
6.34060 2.41599
8
7.90650 4.01746
4.10998 4.18354
4.67289 4.01887
6.33885 4.28388
4.98106 3.82728
5.12379 5.16473
7.84664 4.67693
4.02776 3.87990
20
6.65128 5.47490
6.42743 6.26189
6.35864 4.61611
6.59020 4.54228
4.43967 5.70059
4.38226 5.70536
5.50755 6.18163
7.41971 6.13668
6.71936 3.04496
5.61832 4.23857
5.99424 4.29328
5.60961 4.32998
6.82242 5.79683
5.44693 3.82724
6.70906 3.65736
7.89087 5.68000
6.23300 4.59530
5.92401 4.92329
6.24168 3.81389
6.22671 3.62210
0

Output for the Sample Input

2
5
5
11


import Data.List

f s n =
    let s1 = take n s
        s2 = drop n s
        r1 = reverse s1
        r2 = reverse s2
    in
        [s1++s2, s1++r2, r1++s2, r1++r2, s2++s1, s2++r1, r2++s1, r2++r1]

ans s =
    let l = length s
        p = nub $ sort $ concat $ map (f s) [1..(l-1)]
    in
        length p

main = do
    _ <- getLine
    c <- getContents
    let i = lines c
        o = map ans i
    mapM_ print o

Problem B: Organize Your Train part II

RJ Freight, a Japanese railroad company for freight operations
has recently constructed exchange lines at Hazawa, Yokohama.
The layout of the lines is shown in Figure B-1.

Figure B-1: Layout of the exchange lines

A freight train consists of 2 to 72 freight cars. There are 26
types of freight cars, which are denoted by 26 lowercase letters
from "a" to "z". The cars of the same type are indistinguishable from
each other, and each car's direction doesn't matter either.
Thus, a string of lowercase letters of length 2 to 72 is sufficient
to completely express the configuration of a train.

Upon arrival at the exchange lines, a train is divided into two
sub-trains at an arbitrary position (prior to entering the
storage lines). Each of the sub-trains may have its direction
reversed (using the reversal line). Finally, the two sub-trains
are connected in either order to form the final configuration.
Note that the reversal operation is optional for each of the
sub-trains.

For example, if the arrival configuration is "abcd", the train
is split into two sub-trains of either 3:1, 2:2 or 1:3 cars.
For each of the splitting, possible final configurations are
as follows ("+" indicates final concatenation position):

[3:1]
abc+d cba+d d+abc d+cba
[2:2]
ab+cd ab+dc ba+cd ba+dc cd+ab cd+ba dc+ab dc+ba
[1:3]
a+bcd a+dcb bcd+a dcb+a

Excluding duplicates, 12 distinct configurations are possible.

Given an arrival configuration, answer
the number of distinct configurations which can be
constructed using the exchange lines described above.

Input

The entire input looks like the following.

the number of datasets = m

1st dataset

2nd dataset

...

m-th dataset

Each dataset represents an arriving train, and is a string of
2 to 72 lowercase letters in an input line.

Output

For each dataset, output the number of possible train configurations
in a line. No other characters should appear in the output.

Sample Input

4
aa
abba
abcd
abcde

Output for the Sample Input

1
6
12
18


import Control.Monad
import Control.Applicative
import Data.List
import Debug.Trace

parse :: String -> (Int, String)
parse xs =
    let (prev,t:rst) = break (== ']') xs
        x = read prev
    in ((x + 1) `div` 2, rst)

calc :: [Int] -> Int
calc xs =
    let m = ((length xs) + 1) `div` 2
    in sum $ take m $ sort xs

solve :: [Int] -> String -> (Int, String)
solve stk "" = (calc stk, "")
solve stk (c:cs)
    | c == '['  =
        let (x, rst) = solve [] cs
        in solve (x:stk) rst
    | c == ']'  =
        let x = calc stk
        in (x, cs)
    | otherwise = parse (c:cs)

main :: IO ()
main = do
    n <- readLn
    ls <- replicateM n getLine :: IO [String]
    mapM_ print $ map (fst . solve []) ls

Hierarchical Democracy

The presidential election in Republic of Democratia is carried out through multiple stages as follows.

There are exactly two presidential candidates.

At the first stage, eligible voters go to the polls of his/her electoral district.
The winner of the district is the candidate who takes a majority of the votes.
Voters cast their ballots only at this first stage.

A district of the k-th stage (k > 1) consists of multiple districts of the (k − 1)-th stage. In contrast, a district of the (k − 1)-th stage is a sub-district of one and only one district of the k-th stage. The winner of a district of the k-th stage is the candidate who wins in a majority of its sub-districts of the (k − 1)-th stage.

The final stage has just one nation-wide district. The winner of the final stage is chosen as the president.

You can assume the following about the presidential election of this country.

Every eligible voter casts a vote.

The number of the eligible voters of each electoral district of the first stage is odd.

The number of the sub-districts of the (k − 1)-th stage that constitute a district of the k-th stage (k > 1) is also odd.

This means that each district of every stage has its winner (there is no tie).

Your mission is to write a program that finds a way to win the presidential election with the minimum number of votes.
Suppose, for instance, that the district of the final stage has three sub-districts of the first stage and that the numbers of the eligible voters of the sub-districts are 123, 4567, and 89, respectively.
The minimum number of votes required to be the winner is 107, that is, 62 from the first district and 45 from the third.
In this case, even if the other candidate were given all the 4567 votes in the second district, s/he would inevitably be the loser.
Although you might consider this election system unfair, you should accept it as a reality.

Input

The entire input looks like:

the number of datasets (=n)

1st dataset

2nd dataset

…

n-th dataset

The number of datasets, n, is no more than 100.

The number of the eligible voters of each district and the part-whole relations among districts are denoted as follows.

An electoral district of the first stage is denoted as [c], where c is the number of the eligible voters of the district.

A district of the k-th stage (k > 1) is denoted as [d1d2…dm], where d1, d2, …, dm denote its sub-districts of the (k − 1)-th stage in this notation.

For instance, an electoral district of the first stage that has 123 eligible voters is denoted as [123].
A district of the second stage consisting of three sub-districts of the first stage that have 123, 4567, and 89 eligible voters, respectively, is denoted as [[123][4567][89]].

Each dataset is a line that contains the character string denoting the district of the final stage in the aforementioned notation.
You can assume the following.

The character string in each dataset does not include any characters except digits ('0', '1', …, '9') and square brackets ('[', ']'), and its length is between 11 and 10000, inclusive.

The number of the eligible voters of each electoral district of the first stage is between 3 and 9999, inclusive.

The number of stages is a nation-wide constant.
So, for instance, [[[9][9][9]][9][9]] never appears in the input.
[[[[9]]]] may not appear either since each district of the second or later stage must have multiple sub-districts of the previous stage.

Output

For each dataset, print the minimum number of votes required to be the winner of the presidential election in a line.
No output line may include any characters except the digits with which the number is written.

Sample Input

6
[[123][4567][89]]
[[5][3][7][3][9]]
[[[99][59][63][85][51]][[1539][7995][467]][[51][57][79][99][3][91][59]]]
[[[37][95][31][77][15]][[43][5][5][5][85]][[71][3][51][89][29]][[57][95][5][69][31]][[99][59][65][73][31]]]
[[[[9][7][3]][[3][5][7]][[7][9][5]]][[[9][9][3]][[5][9][9]][[7][7][3]]][[[5][9][7]][[3][9][3]][[9][5][5]]]]
[[8231][3721][203][3271][8843]]

Output for the Sample Input

107
7
175
95
21
3599


import Data.List

main = interact $ unlines . map (show . attwo . map read . words) . init . lines

attwo [n,k,m] = attwo' (n-1) $ take (n-1) $ tail $ dropWhile (/=m) (cycle [1..n])
 where
  attwo' _ [x] = x
  attwo' l xs = attwo' (l-1) (delete x (take l xs'))
   where (x:xs') = drop (mod (k-1) l) (cycle xs)

Problem A: And Then There Was One

Let’s play a stone removing game.

Initially, n stones are arranged on a circle and numbered 1, ... , n clockwise (Figure 1). You are also given two numbers k and m. From this state, remove stones one by one following the rules explained below, until only one remains. In step 1, remove stone m. In step 2, locate the k-th next stone clockwise from m and remove it. In subsequent steps, start from the slot of the stone removed in the last step, make k hops clockwise on the remaining stones and remove the one you reach. In other words, skip (k - 1) remaining stones clockwise and remove the next one. Repeat this until only one stone is left and answer its number.

For example, the answer for the case n = 8, k = 5, m = 3 is 1, as shown in Figure 1.

Figure 1: An example game

Initial state: Eight stones are arranged on a circle.

Step 1: Stone 3 is removed since m = 3.

Step 2: You start from the slot that was occupied by stone 3. You skip four stones 4, 5, 6 and 7 (since k = 5), and remove the next one, which is 8.

Step 3: You skip stones 1, 2, 4 and 5, and thus remove 6. Note that you only count stones that are still on the circle and ignore those already removed. Stone 3 is ignored in this case.

Steps 4-7: You continue until only one stone is left. Notice that in later steps when only a few stones remain, the same stone may be skipped multiple times. For example, stones 1 and 4 are skipped twice in step 7.

Final State: Finally, only one stone, 1, is on the circle. This is the final state, so the answer is 1.

Input

The input consists of multiple datasets each of which is formatted as follows.

n k m

The last dataset is followed by a line containing three zeros. Numbers in a line are separated by a single space. A dataset satisfies the following conditions.

2 ≤ n ≤ 10000, 1 ≤ k ≤ 10000, 1 ≤ m ≤ n

The number of datasets is less than 100.

Output

For each dataset, output a line containing the stone number left in the final state. No extra characters such as spaces should appear in the output.

Sample Input

8 5 3
100 9999 98
10000 10000 10000
0 0 0

Output for the Sample Input

1
93
2019


import Data.List

ans ([0]:_) = []
ans (_:x:r) =
  let s = sort x
      s'= drop 1 s
      d = minimum $ map (\ (a,b) -> a-b ) $ zip s' s
  in
    d:(ans r)

main = do
  c <- getContents
  let i = map (map read) $ map words $ lines c :: [[Int]]
      o = ans i
  mapM_ print o

Selection of Participants of an Experiment

Dr. Tsukuba has devised a new method of programming training.
In order to evaluate the effectiveness of this method,
he plans to carry out a control experiment.
Having two students as the participants of the experiment,
one of them will be trained under the conventional method
and the other under his new method.
Comparing the final scores of these two,
he will be able to judge the effectiveness of his method.

It is important to select two students having the closest possible scores,
for making the comparison fair.
He has a list of the scores of all students
who can participate in the experiment.
You are asked to write a program which selects two of them
having the smallest difference in their scores.

Input

The input consists of multiple datasets, each in the following format.

n

a1 a2 … an

A dataset consists of two lines.
The number of students n is given in the first line.
n is an integer satisfying 2 ≤ n ≤ 1000.
The second line gives scores of n students.
ai (1 ≤ i ≤ n) is the score of the i-th student, which is a non-negative integer not greater than 1,000,000.

The end of the input is indicated by a line containing a zero.
The sum of n's of all the datasets does not exceed 50,000.

Output

For each dataset, select two students with the smallest difference in their scores,
and output in a line (the absolute value of) the difference.

Sample Input

5
10 10 10 10 10
5
1 5 8 9 11
7
11 34 83 47 59 29 70
0

Output for the Sample Input

0
1
5


mov (x,y) (dir,len) =
  case dir of
    "N" -> (x,y+len)
    "E" -> (x+len,y)
    "W" -> (x-len,y)
    "S" -> (x,y-len)

inside s d j = ( (s <= j) && (j <= d) ) || ( (d <= j) && (j <= s) )

pick :: (Int,Int) -> (Int,Int) -> [(Int,Int)] -> [(Int,Int)]
pick _ _ [] = []
pick s@(sx,sy) d@(dx,dy) (j@(jx,jy):js) =
  if (inside sx dx jx) && (inside sy dy jy)
  then pick s d js
  else j:(pick s d js)

ans' :: [(Int,Int)] -> (Int,Int) -> [(String,Int)] -> [(Int,Int)]
ans' [] _ _ = []
ans' j s [] = [s]
ans' j s (c:cs) =
  let d = mov s c
      j'= pick s d j
  in
    ans' j' d cs

ans x =
  let n = read $ head $ head x :: Int
      j = map (\[a,b]->(read a,read b)) $ take n $ drop 1 x :: [(Int,Int)]
      m = read $ head $ head $ drop (n+1) x :: Int
      c = map (\[a,b]->(a,read b)) $ take m $ drop (n+2) x :: [(String,Int)]
      r = drop (n+m+2) x
      a = ans' j (10,10) c
      b = if a == [] then "Yes" else "No"
  in
    if n == 0 then [] else (b:(ans r))

main = do
  c <- getContents
  let i = map words $ lines c
      o = ans i
  mapM_ putStrLn o

Mysterious Gems

宇宙暦 1603〜1867 年，人々はその時代のことを EDO 時代と呼ぶ．EDO とは当時最先端の宇宙航行技術，Enhanced Driving Operation のことであり、1603 年に Dr.Izy によって開発された．

あなたは宇宙冒険家であり，宇宙を飛び回って様々な惑星を冒険していた．その冒険の途中で，あなたはとても不思議な惑星を発見した．その惑星には，至るところに七色に輝く不思議な宝石が落ちていた．あなたはその惑星への降下を試みようと考えたが，重大な問題のためにそれは不可能であることがわかった．その惑星の空気には，人間が触れただけで即死してしまうような猛毒の成分が含まれていたのだ．

そこで，あなたはロボットを使って宝石を回収することを考えついた．あなたはその惑星の周回軌道にて待機する．そして，降下させたロボットを遠隔操作することによって宝石を回収するのだ．あなたは，ロボットに「移動する方向」と「移動する距離」の組からなる命令の列によってロボットを遠隔操作する．ロボットは移動経路上（到達点を含む）に宝石を見つけると，それらを全て回収する．

あなたの仕事は，ロボットが与えられた全ての命令の実行を終えたときに，全ての宝石を回収することができたかどうかを判定するプログラムを書くことである．

なお，ロボットが不思議な宝石を回収する範囲はそれほど広くない．そのため，ロボットが移動する範囲は全て 2 次元の平面で表すことができる．そして，ロボットが移動する範囲は (0,0) および (20,20) をそれぞれ左下隅および右上隅とする正方形の内部（境界線を含む）である．ロボットは常に範囲の中央，すなわち (10,10) の座標に降下する．また，全ての宝石は中央以外の格子点上にあることが保証されている．

Input

入力は複数のデータセットにより構成される．

それぞれのデータセットの先頭行には，単一の正の整数 N (1 <= N <= 20) が含まれる。これはロボットが移動可能な範囲内にある不思議な宝石の個数を表す．次の N 行には，それぞれ xi および yi (0 <= xi , yi <= 20) が含まれ，これは i 番目の不思議な宝石の落ちている座標を表す．なお，1 つの場所に複数の宝石が落ちていることはない．

次の行には単一の整数 M (1 <= M <= 30) が含まれ，これはロボットに与えた命令の個数を表す．この後の M 行にはそれぞれ dj とひとつの正の整数 lj が含まれる．これは j 番目の命令における方向および移動量を表す．ただし，方向は N，E，S，W のいずれかの文字であり，順に北，東，南，西を表す（北は y 軸の正方向，東は x 軸の正方向）．なお，ロボットが移動可能な範囲を超えるような命令は与えられないことが保証されている．

入力は N = 0 のときに終了し，これはデータセットに含まれない．

Output

それぞれのデータセットについて，ロボットが全ての宝石を収集できるときは「Yes」と，そうでないときは「No」と 1 行に出力しなさい．

Sample Input

2
10 11
11 12
2
N 2
E 1
2
10 11
11 12
2
N 2
W 1
3
0 15
5 10
5 15
5
W 10
S 10
N 20
E 10
S 10
0

Output for the Sample Input

Yes
No
No


import qualified Control.Monad as C
import qualified Data.List     as L
import Control.Applicative ((<$>))

solve :: Int -> IO ()
solve n = do
    rideAndLeftTimes <- C.forM [1..n] $ \_ -> do
        [ride, left] <- map read . words . filter (/= ':') <$> getLine :: IO [Int]
        return (ride, left)
    let rides = map (\x -> (x,  1)) $ map fst rideAndLeftTimes
    let lefts = map (\x -> (x, -1)) $ map snd rideAndLeftTimes
    print . maximum . scanl (+) 0 . map snd . L.sort $ rides ++ lefts
    main

main :: IO ()
main = do
    n <- read <$> getLine :: IO Int
    C.when (n /= 0) $ solve n

Osaki

大崎

English text is not available in this practice contest.

山手線は東京 23 区内に敷設されている環状鉄道路線である．総路線距離は 34.5km であり，1 周にはおよそ 1 時間を要する．駅は全部で 29 駅存在する．ラインカラーはウグイス色である．ピーク時の混雑率は 200% を超え，日本の鉄道路線の中で最も混雑している路線の 1 つである．最も混雑する時間帯では 3 分に 1 本の列車が走っており，東京に初めて来た人々はその光景に驚くものである．

鉄子さんは山手線を愛してやまない生粋の鉄道好きである．ある日，彼女は愛読書である JR 時刻表を読みながら次の疑問に至った．「山手線では一日に何台の車両が使われているのだろう？」

彼女は時刻表から運行に最低限必要な車両の台数を割り出そうとした．しかし，列車の本数が非常に多かったので，彼女一人の力では到底数え切れそうにない．そこで彼女は優秀なプログラマーであるあなたに助けを求めた．

あなたの仕事は与えられた時刻表から山手線の運行に要する車両の最低台数を求めるプログラムを書くことである．山手線は環状路線であることから，その時刻表は便宜上「大崎駅」を始発駅および終着駅として表記されることが多い．そのため，彼女から渡された時刻表にも各列車の大崎駅における発時刻および着時刻のみが記されている．

なお，実際の山手線では起こりえないが，状況設定を簡単にするため，ここでは大崎駅の到着直後に列車が大崎駅を出発可能であると考えることにする．また，鉄子さんが写した時刻に誤りがあったり，鉄子さんの妄想によって勝手に加えられた列車が時刻表に紛れ込んだりしている場合もあるが，あなたはそれらを見抜くことができないので，あくまでも書かれたとおりの時刻に対して台数を求めなければならない．

きちんと動作するプログラムを書けば，彼女が列車内デートに誘ってくれるかもしれない．もっとも，誘いに乗るか断るかはあなた次第であるが．

Input

入力は複数のデータセットから構成される．各データセットは次の形式になっている．

n

hh:mm:ss hh:mm:ss

hh:mm:ss hh:mm:ss

...

hh:mm:ss hh:mm:ss

1 行目の整数 n は時刻表に含まれる列車の本数である．この値は 10,000 を超えないことが保証されている．2 行目から n + 1 行目までの n 行には各列車の大崎駅の発時刻および着時刻がこの順番で与えられ，発時刻と着時刻の間は 1 つの空白で区切られている．各時刻は hh:mm:ss の形式で表現され，hh が時，mm が分，ss が秒を表している．それぞれの値の範囲は 0 ≦ hh < 24, 0 ≦ mm < 60, 0 ≦ ss < 60である．これらの数値は全て 2 桁となるように，必要に応じて先頭に 0 が付け加えられている．

夜の 24:00 をまたいで運行されるような列車は含まれない．したがって，常に発時刻は常に着時刻よりも前の時刻である．

入力の終了は n = 0 によって示される．これはデータセットには含まれない．

Output

各データセットに対して，最低限必要となる車両の台数を 1 行に出力しなさい．

Sample Input

3
05:47:15 09:54:40
12:12:59 12:13:00
16:30:20 21:18:53
6
00:00:00 03:00:00
01:00:00 03:00:00
02:00:00 03:00:00
03:00:00 04:00:00
03:00:00 05:00:00
03:00:00 06:00:00
0

Output for the Sample Input

1
3


import Control.Applicative
import Control.Monad
import Data.Bool (bool)

main :: IO ()
main = do
  [a, b] <- f
  unless (a == 0 && b == 0) $ do
    putStrLn $ solve a b
    main
  where
    f = map read <$> words <$> getLine

solve :: Int -> Int -> String
solve a b = bool "a" "b" $ f a < f b
  where
    f x = let fs = fcs x in 2 * (head fs) - sum fs

fcs x = f [] x 2
  where
    f fs x d
      | x < d ^ 2 = if x == 1 then fs else x : fs
      | x `mod` d == 0 = f (d : fs) (g x d) (d + 1)
      | otherwise = f fs x (d + 1)
    g x d
      | x `mod` d == 0 = g (x `div` d) d
      | otherwise = x

Problem A: Everlasting...?

Everlasting Sa-Ga, a new, hot and very popular role-playing game, is out on October 19, 2008.
Fans have been looking forward to a new title of Everlasting Sa-Ga.

Little Jimmy is in trouble. He is a seven-year-old boy, and he obtained the Everlasting Sa-Ga
and is attempting to reach the end of the game before his friends. However, he is facing difficulty
solving the riddle of the first maze in this game -- Everlasting Sa-Ga is notorious in extremely
hard riddles like Neverending Fantasy and Forever Quest.

The riddle is as follows. There are two doors on the last floor of the maze: the door to the
treasure repository and the gate to the hell. If he wrongly opens the door to the hell, the game
is over and his save data will be deleted. Therefore, he should never open the wrong door.

So now, how can he find the door to the next stage? There is a positive integer given for each
door -- it is a great hint to this riddle. The door to the treasure repository has the integer that
gives the larger key number. The key number of a positive integer n is the largest prime factor
minus the total sum of any other prime factors, where the prime factors are the prime numbers
that divide into n without leaving a remainder. Note that each prime factor should be counted
only once.

As an example, suppose there are doors with integers 30 and 20 respectively. Since 30 has three
prime factors 2, 3 and 5, its key number is 5 - (2 + 3) = 0. Similarly, since 20 has two prime
factors 2 and 5, its key number 20 is 5 - 2 = 3. Jimmy therefore should open the door with 20.

Your job is to write a program to help Jimmy by solving this riddle.

Input

The input is a sequence of datasets. Each dataset consists of a line that contains two integers a
and b separated by a space (2 ≤ a, b ≤ 106 ). It is guaranteed that key numbers of these integers
are always different.

The input is terminated by a line with two zeros. This line is not part of any datasets and thus
should not be processed.

Output

For each dataset, print in a line ‘a’ (without quotes) if the door with the integer a is connected
to the treasure repository; print ‘b’ otherwise. No extra space or character is allowed.

Sample Input

10 15
30 20
0 0

Output for the Sample Input

a
b


import Control.Applicative
import Control.Monad
import Data.Vector.Unboxed (Vector, (!), (//))
import qualified Data.Vector.Unboxed as V

main :: IO ()
main = do
  n <- readLn
  unless (n == 0) $ do
    print $ solve n
    main

solve :: Int -> Int
solve n = let lv = n `div` 2 + 2
              v = V.unfoldr (\i -> if 2 * i <= n + 2
                                   then Just (i * (i + 1) `div` 2, i + 1)
                                   else Nothing) 0
          in length $ do
            i <- [0 .. lv - 2]
            guard $ bsearch v (v ! i + n) (i + 2) lv
            return ()

bsearch :: Vector Int -> Int -> Int -> Int -> Bool
bsearch v x l r
  | l >= r = False
  | x > y = bsearch v x (m + 1) r
  | x < y = bsearch v x l m
  | otherwise = True
  where
    m = (l + r) `div` 2
    y = v ! m

Problem A: Sum of Consecutive Integers

あなたは数か月に渡る受験戦争を勝ち抜き，晴れてICPC大学に入学することができた．入学手続きの日，大学のキャンパス内では熱狂的なサークルの勧誘活動が行われており，あなたは大量のパンフレットを受け取って帰ってきた．部屋に戻ってきたあなたは受け取ったパンフレットの中から気になる一枚を見つけた．そのパンフレットは大学の広報部から渡されたものだった．

パンフレットには以下のような問題が記されていた．

和が N となるような，連続する2つ以上の正の整数の組み合わせは，何組存在するでしょうか？例えば， 9 は 2+3+4 と 4+5 の 2通りの組み合わせがあります．

この問題の答えが気になったあなたは，プログラムを書いてその答えを調べることにした．したがって，あなたの仕事は，入力として与えられる正の整数 N に対して，問題の答えを出力するプログラムを書くことである．

Input

入力はデータセットの並びである．各データセットはひとつの整数 N からなる一行である．ここで 1 ≤ N ≤ 1000 である．

入力の終りは，ひとつのゼロからなる一行で示される．

Output

出力は，入力の各データセットの表す正の整数に対する問題の答えを，入力データセットの順序通りに並べたものである．それ以外の文字が出力にあってはならない．

Sample Input

9
500
0

Output for the Sample Input

2
3


{-# LANGUAGE BangPatterns #-}
import Control.Monad
import qualified Data.ByteString.Char8  as B
import Data.Array.Unboxed
import Data.Functor

main :: IO ()
main = do
  n <- readLn
  replicateM n iterateSolveDp
  return ()

iterateSolveDp = do
  x <- B.unpack <$> B.getLine
  y <- B.unpack <$> B.getLine
  let n = length x
      m = length y
      a = listArray (0, n-1) x :: Array Int Char
      b = listArray (0, m-1) y :: Array Int Char
      dp :: Array (Int, Int) Int
      dp = listArray ((0, 0), (n, m)) $ map f [(i, j)|i<-[0..n],j<-[0..m]]
      f (0, _) = 0
      f (_, 0) = 0
      f (i, j)
        | a!(i-1) == b!(j-1) = 1 + dp!(i-1, j-1)
        | otherwise = max (dp!(i, j-1)) (dp!(i-1, j))
  print $ dp!(n, m)

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Longest Common Subsequence

For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \{a,b,c,b,d,a,b\}$ and $Y = \{b,d,c,a,b,a\}$, the sequence $\{b,c,a\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\{b,c,a\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\{b,c,b,a\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\{b,c,b,a\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.

Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.

Input

The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.

Output

For each dataset, print the length of LCS of $X$ and $Y$ in a line.

Constraints

$1 \leq q \leq 150$

$1 \leq$ length of $X$ and $Y$ $\leq 1,000$

$q \leq 20$ if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


lcs :: (String,String) -> Int -> Int
lcs ([],_) n = n
lcs (_,[]) n = n
lcs (ax@(x:xs),ay@(y:ys)) n
  | x == y    = lcs (xs,ys) (n+1)
  | otherwise = max (lcs (ax,ys) n) (lcs (xs,ay) n)

main = do
  getLine
  inputs <- fmap lines getContents
  let targets = zip (takeOnlyOdd inputs) (takeOnlyEven inputs)
  mapM_ putStrLn $ map (\x -> show $ lcs x 0) targets

takeOnlyEven :: [a] -> [a]
takeOnlyEven xs = map snd . filter (\(i, n) -> i `mod` 2 == 0) $ zip [1..] xs
takeOnlyOdd :: [a] -> [a]
takeOnlyOdd xs = map snd . filter (\(i, n) -> i `mod` 2 == 1) $ zip [1..] xs


import Control.Monad (replicateM)

main :: IO ()
main = do
    n <- readLn
    is <- replicateM n $ do
        str1 <- getLine
        str2 <- getLine
        return (str1,str2)
    mapM_ (print . lcs) is

lcs :: (String, String) -> Int
lcs (xs,ys) = lcs' (length xs) (length ys)
    where
        lcs' 0 _ = 0
        lcs' _ 0 = 0
        lcs' i j | xs !! (i-1) == ys !! (j-1) = lcs' (i-1) (j-1) + 1
                 | otherwise = lcs' i (j-1) `max` lcs' (i-1) j


import Control.Monad (replicateM_)
import qualified Data.Vector as V

main :: IO ()
main = do
    n <- readLn
    replicateM_ n $ do
        str1 <- getLine
        str2 <- getLine
        print $ lcs (str1,str2)

lcs :: (String,String) -> Int
lcs (xs,ys) = lcsTable (lx,ly)
    where
        lx = length xs
        ly = length ys
        xs' = V.fromList xs
        ys' = V.fromList ys
        idx (x,y) = x + y*(lx+1)
        xdi i = (i `mod` (lx+1), i `div` (lx+1))
        lcsTable = (V.map (lcs'.xdi) (V.enumFromN 0 (idx (lx,ly)+1)) V.!) . idx
        lcs' (0,_) = 0
        lcs' (_,0) = 0
        lcs' (i,j)
          | xs' V.! (i-1) == ys' V.! (j-1) = lcsTable (i-1,j-1) + 1
          | otherwise = lcsTable (i,j-1) `max` lcsTable (i-1,j)


-- | Main entry point to the application.
module Main where

import Control.Applicative
import Control.Monad
import Data.List
import Debug.Trace
import Text.Printf
import Data.Array

isPrime n = null [i | i <- takeWhile (\x -> x * x <= n) primes, n `rem` i == 0]
primes = 2:3:[x | i <- [1..], j <- [-1,1], let x = 6*i+j, isPrime x]

-- | The main entry point.
main :: IO ()
main = do
    _ <- getLine
    ns <- concatMap (fmap (read :: String -> Int) . words) . lines <$> getContents
    putStrLn $ show $ length $ filter isPrime ns

Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4


import Control.Applicative
import qualified Data.ByteString.Char8 as BC
import Data.Maybe (fromJust)
import Data.List

maxDiff :: (Ord a , Num a)=> [a] -> a
maxDiff xs =  fst $ foldl'
    (\(ma',mi') n -> (max ma' (n-mi'), min mi' n)) (- (head xs),head xs) (tail xs)

readInts :: IO [Int]
readInts = map (fst . fromJust . BC.readInt) . BC.lines <$> BC.getContents

main = do
    _ <- getLine
    readInts >>= print . maxDiff

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1


import Control.Arrow
import Control.Monad.State.Strict

main :: IO()
main = getLine >> getContents >>= print.fst.(\(x:y:ys) -> solve ys (y- x, min x y)).map read.lines

solve :: [Int] -> (Int, Int) -> (Int, Int)
solve ys = execState $ do
            forM_ ys $ \y -> do
              (a, b) <- get
              modify $! (max (y - b)) *** (min y)
            return ()


import qualified Data.ByteString.Char8 as BC
import Data.IORef
import Control.Monad(when)
import Control.Applicative((*>))
import Data.Foldable(for_)
import Data.Maybe(fromJust)

main :: IO()
main = BC.getLine *> BC.getContents >>= solve.map (fst.fromJust.BC.readInt).BC.lines >>= print

solve :: [Int] -> IO Int
solve (x : y : xs) = do
                a <- newIORef (y - x)
                b <- newIORef (min x y)
                for_ xs $ \z -> do
                    a' <- readIORef a
                    b' <- readIORef b
                    when (z - b' > a') $ writeIORef a (z - b')
                    when (z < b')      $ writeIORef b z
                readIORef a


import Control.Applicative

bubbleSort :: [Int] -> (Int ,[Int])
bubbleSort xs = loop (1, 0, xs)
  where
    n = length xs - 2
    loop (0, m, xs) = (m, xs)
    loop (1, m, xs) = loop $ foldr f (0, m, xs) [0 .. n]
    f i  (f, m, xs) = if b > c
                      then (1, m + 1, (as ++ c : b : ds))
                      else (f, m, as ++ bs)
      where (as, bs@(b : c : ds)) = splitAt i xs

main :: IO ()
main = do
  _  <- getLine
  xs <- map read . words <$> getLine
  let (m, ys) = bubbleSort xs
  putStrLn $ unwords $ map show ys
  print m

Bubble Sort

Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

BubbleSort(A)
1 for i = 0 to A.length-1
2 for j = A.length-1 downto i+1
3 if A[j] < A[j-1]
4 swap A[j] and A[j-1]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 4 of the pseudocode.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by spaces characters.

Output

The output consists of 2 lines.

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Constraints

1 ≤ N ≤ 100

Sample Input 1

5
5 3 2 4 1

Sample Output 1

1 2 3 4 5
8

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
9


import qualified Data.Vector         as V
import qualified Data.Vector.Mutable as VM
import Control.Applicative
import Control.Monad
import Data.IORef
import Text.Printf

type Process = (String, Int)

roundRobin :: Int -> [Process] -> IO ()
roundRobin q xs = do
  queue <- V.thaw $ V.fromList (xs ++ [("String", 0)])
  -- front <- newIORef 0
  -- rear  <- newIORef n
  loop 0 queue 0 n
  where
    n = length xs
    loop :: Int -> VM.IOVector (String, Int) -> Int -> Int -> IO ()
    loop t vec front rear = do
      -- f <- readIORef front
      -- r <- readIORef rear
      when (front /= rear) $ do
        -- i <- readIORef front
        -- writeIORef front (if i == n then 0 else i + 1)
        (name, time) <- VM.read vec front
        if time <= q
          then do
          printf "%s %d\n" name (t + time)
          loop (t + time) vec (if front == n then 0 else front + 1) rear
          else do
          -- j <- readIORef rear
          -- writeIORef rear (if j == n then 0 else j + 1)
          VM.write vec rear (name, time - q)
          loop (t + q) vec (if front == n then 0 else front + 1) (if rear == n then 0 else rear + 1)

main :: IO ()
main = do
  [n, q] <- map read . words <$> getLine
  xs <- map (toTuple . words) <$> replicateM n getLine
  roundRobin q xs
    where toTuple [n, t]  = (n, read t)

There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C


import Control.Monad
import Control.Applicative

main :: IO ()
main = do
  [n, q] <- map read . words <$> getLine
  queue <- map ((\[x, y] -> (x, read y)) . words) <$> replicateM n getLine :: IO [(String, Int)]
  putStrLn . init . unlines $ calc queue q 0 []

calc :: [(String, Int)] -> Int -> Int -> [String] -> [String]
calc [] _ _ ans = reverse ans
calc ((name, time):xs) n total ans
  | time > n = calc (xs ++ [(name, time - n)]) n (total + n) ans
  | otherwise = calc xs n (total + time) $ (unwords [name, show $ total + time]) : ans


type TotalTime = Int
type UnitTime = Int

roundRobin :: [(String, Int)] -> [(String, Int)] -> UnitTime -> TotalTime -> [(String, Int)]
roundRobin [] ys _ _ = ys
roundRobin (x:xs) ys u t
  | (snd x) == consume = roundRobin xs ((fst x, total):ys) u total
  | otherwise          = roundRobin (xs ++ [(fst x, snd x - consume)]) ys u total
  where consume = min (snd x) u
        total = t + consume

main = do
  u <- fmap (read . (!! 1) . words) getLine
  input <- fmap ((map words) . lines) getContents
  let queue = map (\[x, y] -> (x, read y))  input
  let result = roundRobin queue [] u 0
  mapM_ putStrLn (reverse $ map (\(x, y) -> x ++ " " ++ show y) result)


{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative
import Data.ByteString.Char8
import qualified Data.ByteString.Char8 as DBC8
import Data.Foldable (toList)
import Data.Sequence (Seq)
import qualified Data.Sequence as S

removeOne :: ByteString -> Seq ByteString -> Seq ByteString
removeOne x seq =
  case S.viewl seq of
    S.EmptyL  -> S.empty
    s S.:< ss ->
      if x == s
         then ss
         else s S.<| (removeOne x ss)

exec :: [ByteString] -> Seq ByteString -> Seq ByteString
exec ["insert", n]   seq = n S.<| seq
exec ["delete", n]   seq = removeOne n seq
exec ["deleteFirst"] seq = let (s  S.:< ss) = S.viewl seq in ss
exec ["deleteLast"]  seq = let (ss S.:>  s) = S.viewr seq in ss

printSeq :: ByteString -> [ByteString] -> IO ()
printSeq _ []       = DBC8.putStrLn "" >> return ()
printSeq sep (x:xs) = do
  DBC8.putStr sep
  DBC8.putStr x
  printSeq " " xs

main :: IO ()
main = do
  n   <- read . DBC8.unpack <$> DBC8.getLine :: IO Int
  seq <- readCommand n S.empty
  printSeq "" (toList seq)
  where
    readCommand :: Int -> Seq ByteString -> IO (Seq ByteString)
    readCommand 0 seq = return seq
    readCommand n seq = do
      cmds <- DBC8.words <$> DBC8.getLine
      readCommand (n-1) (exec cmds seq)

Doubly Linked List

Your task is to implement a double linked list.

Write a program which performs the following operations:

insert x: insert an element with key x into the front of the list.

delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.

deleteFirst: delete the first element from the list.

deleteLast: delete the last element from the list.

Input

The input is given in the following format:

n

command1

command2

...

commandn

In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format:

insert x

delete x

deleteFirst

deleteLast

Output

Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space.

Constraints

The number of operations ≤ 2,000,000

The number of delete operations ≤ 20

0 ≤ value of a key ≤ 109

The number of elements in the list does not exceed 106

For a delete, deleteFirst or deleteLast operation, there is at least one element in the list.

Sample Input 1

7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5

Sample Output 1

6 1 2

Sample Input 2

9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast

Sample Output 2

1


{-# OPTIONS_GHC -O2 #-}
-- {-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE MultiWayIf #-}
-- {-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE TupleSections #-}

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function (on)
import           Data.Ord (comparing)
import           Data.Monoid (mappend)
import           Data.Array
-- import           Data.Array.Unboxed
-- import           Data.Array.IArray
-- import           Data.Array.ST
-- import           Data.Array.MArray
-- import           Data.Array.Unsafe
import           Data.Ix
import           Data.Maybe
-- import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
-- import           Data.Graph
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntSet (IntSet)
-- import qualified Data.IntSet as IntSet
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR(..), ViewL(..), Seq)
-- import qualified Data.Sequence              as Seq
-- import           Data.Foldable (toList, minimumBy)
import           Debug.Trace

data Query = Insert Int | Delete Int | DeleteFirst | DeleteLast

data Deque a = Q [a] Int [a] Int deriving (Show)

emptyQ :: Deque a
emptyQ = Q [] 0 [] 0

viewQ :: Deque a -> [a]
viewQ (Q xs _ ys _) = xs ++ reverse ys

insertQ :: a -> Deque a -> Deque a
insertQ a (Q x lx y ly) = chk $ Q (a:x) (lx + 1) y ly

deleteQ :: Eq a => a -> Deque a -> Deque a
deleteQ a (Q x lx y ly)
  | a `elem` x = chk $ Q (delete a x) (lx - 1) y ly
  | a `elem` y = chk $ Q x lx (reverse $ delete a (reverse y)) (ly - 1)
  | otherwise = chk $ Q x lx y ly

deleteFirstQ :: Deque a -> Deque a
deleteFirstQ (Q (_:xs) lx y ly) = chk $ Q xs (lx - 1) y ly
deleteFirstQ (Q [] _ [_] _) = chk emptyQ

deleteLastQ :: Deque a -> Deque a
deleteLastQ (Q x lx (_:ys) ly) = chk $ Q x lx ys (ly - 1)

chk :: Deque a -> Deque a
chk (Q [] 0 [] 0) = Q [] 0 [] 0
chk (Q [x] 1 [] 0) = Q [] 0 [x] 1
chk (Q [] 0 y ly) = chk $ Q (reverse y) ly [] 0
chk (Q (x:xs) lx y ly) = if lx > ly
  then Q [x] 1 (y++reverse xs) (lx+ly)
  else Q (x:xs) lx y ly

main = do
  n <- readInt1 <$> BS.getLine
  qs <- map myread <$> replicateM n BS.getLine
  putIntN $ solve qs

solve = viewQ . foldl f emptyQ where
  f' q query = traceShowId $ f q query
  f q (Insert a) = insertQ a q
  f q (Delete a) = deleteQ a q
  f q DeleteFirst = deleteFirstQ q
  f q DeleteLast = deleteLastQ q

myread :: BS.ByteString -> Query
myread = f . BS.words where
  f (x:xs)
    | x == "insert" = Insert (readInt1 $ head xs)
    | x == "delete" = Delete (readInt1 $ head xs)
    | x == "deleteFirst" = DeleteFirst
    | x == "deleteLast" = DeleteLast

--  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --

format :: Show a => Maybe a -> IO ()
format Nothing = putStrLn "NO"
format (Just a) = putStrLn "YES" >> print a

-- [1,2,3] -> 1 2 3
putIntN :: [Int] -> IO ()
putIntN [] = return ()
putIntN xs = BL.putStrLn . toLazyByteString . foldl1 mappend . intersperse (char8 ' ') $ map intDec xs

readInt1 :: BS.ByteString -> Int
readInt1 = fst . fromJust . BS.readInt

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readIntN

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readIntN

readIntN :: BS.ByteString -> [Int]
readIntN =  map readInt1 . BS.words

readInt641 :: BS.ByteString -> Int64
readInt641 = fromIntegral . fst . fromJust . BS.readInteger

readInt642 :: BS.ByteString -> (Int64,Int64)
readInt642 = toTuple . readInt64N

readInt643 :: BS.ByteString -> (Int64,Int64,Int64)
readInt643 = toTriple . readInt64N

readInt64N :: BS.ByteString -> [Int64]
readInt64N =  map readInt641 . BS.words

readInteger1 :: BS.ByteString -> Integer
readInteger1 = fst . fromJust . BS.readInteger

readInteger2 :: BS.ByteString -> (Integer,Integer)
readInteger2 = toTuple . readIntegerN

readInteger3 :: BS.ByteString -> (Integer,Integer,Integer)
readInteger3 = toTriple . readIntegerN

readIntegerN :: BS.ByteString -> [Integer]
readIntegerN =  map readInteger1 . BS.words

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

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

fromTuple :: (a, a) -> [a]
fromTuple (x, y) = [x, y]

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

-- if not applying, use "const"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)

-- @since 4.8.0.0
sortOn' :: Ord b => (a -> b) -> [a] -> [a]
sortOn' f =
  map snd . sortBy (comparing fst) . map (\x -> let y = f x in y `seq` (y, x))


{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE TupleSections #-}

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function (on)
import           Data.Ord (comparing)
import           Data.Monoid (mappend)
import           Data.Array
-- import           Data.Array.Unboxed
-- import           Data.Array.IArray
-- import           Data.Array.ST
-- import           Data.Array.MArray
-- import           Data.Array.Unsafe
import           Data.Ix
import           Data.Maybe
-- import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
-- import           Data.Graph
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntSet (IntSet)
-- import qualified Data.IntSet as IntSet
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR(..), ViewL(..), Seq)
-- import qualified Data.Sequence              as Seq
-- import           Data.Foldable (toList, minimumBy)
import           Debug.Trace

data Query = Insert Int | Delete Int | DeleteFirst | DeleteLast

data Deque a = Q [a] Int [a] Int deriving (Show)

emptyQ :: Deque a
emptyQ = Q [] 0 [] 0

viewQ :: Deque a -> [a]
viewQ (Q xs _ ys _) = xs ++ reverse ys

insertQ :: a -> Deque a -> Deque a
insertQ a (Q x lx y ly) = chk $ Q (a:x) (lx + 1) y ly

deleteQ :: Eq a => a -> Deque a -> Deque a
deleteQ a (Q x lx y ly)
  | a `elem` x = chk $ Q (delete a x) (lx - 1) y ly
  | a `elem` y = chk $ Q x lx (reverse $ delete a (reverse y)) (ly - 1)
  | otherwise = chk $ Q x lx y ly

deleteFirstQ :: Deque a -> Deque a
deleteFirstQ (Q (_:xs) lx y ly) = chk $ Q xs (lx - 1) y ly
deleteFirstQ (Q [] _ [_] _) = chk emptyQ

deleteLastQ :: Deque a -> Deque a
deleteLastQ (Q x lx (_:ys) ly) = chk $ Q x lx ys (ly - 1)

chk :: Deque a -> Deque a
chk (Q [] 0 [] 0) = Q [] 0 [] 0
chk (Q [x] 1 [] 0) = Q [] 0 [x] 1
chk (Q [] 0 y !ly) = chk $ Q (reverse y) ly [] 0
chk (Q (x:xs) !lx y !ly) = if lx > ly
  then Q [x] 1 (y++reverse xs) (lx+ly)
  else Q (x:xs) lx y ly

main = do
  n <- readInt1 <$> BS.getLine
  qs <- map myread <$> replicateM n BS.getLine
  putIntN $ solve qs

solve = viewQ . foldl f emptyQ where
  f' q query = traceShowId $ f q query
  f q (Insert a) = insertQ a q
  f q (Delete a) = deleteQ a q
  f q DeleteFirst = deleteFirstQ q
  f q DeleteLast = deleteLastQ q

myread :: BS.ByteString -> Query
myread = f . BS.words where
  f (x:xs)
    | x == "insert" = Insert (readInt1 $ head xs)
    | x == "delete" = Delete (readInt1 $ head xs)
    | x == "deleteFirst" = DeleteFirst
    | x == "deleteLast" = DeleteLast

--  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --

format :: Show a => Maybe a -> IO ()
format Nothing = putStrLn "NO"
format (Just a) = putStrLn "YES" >> print a

-- [1,2,3] -> 1 2 3
putIntN :: [Int] -> IO ()
putIntN [] = return ()
putIntN xs = BL.putStrLn . toLazyByteString . foldl1 mappend . intersperse (char8 ' ') $ map intDec xs

readInt1 :: BS.ByteString -> Int
readInt1 = fst . fromJust . BS.readInt

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readIntN

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readIntN

readIntN :: BS.ByteString -> [Int]
readIntN =  map readInt1 . BS.words

readInt641 :: BS.ByteString -> Int64
readInt641 = fromIntegral . fst . fromJust . BS.readInteger

readInt642 :: BS.ByteString -> (Int64,Int64)
readInt642 = toTuple . readInt64N

readInt643 :: BS.ByteString -> (Int64,Int64,Int64)
readInt643 = toTriple . readInt64N

readInt64N :: BS.ByteString -> [Int64]
readInt64N =  map readInt641 . BS.words

readInteger1 :: BS.ByteString -> Integer
readInteger1 = fst . fromJust . BS.readInteger

readInteger2 :: BS.ByteString -> (Integer,Integer)
readInteger2 = toTuple . readIntegerN

readInteger3 :: BS.ByteString -> (Integer,Integer,Integer)
readInteger3 = toTriple . readIntegerN

readIntegerN :: BS.ByteString -> [Integer]
readIntegerN =  map readInteger1 . BS.words

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

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

fromTuple :: (a, a) -> [a]
fromTuple (x, y) = [x, y]

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

-- if not applying, use "const"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)

-- @since 4.8.0.0
sortOn' :: Ord b => (a -> b) -> [a] -> [a]
sortOn' f =
  map snd . sortBy (comparing fst) . map (\x -> let y = f x in y `seq` (y, x))


{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE TupleSections #-}

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function (on)
import           Data.Ord (comparing)
import           Data.Monoid (mappend)
import           Data.Array
-- import           Data.Array.Unboxed
-- import           Data.Array.IArray
-- import           Data.Array.ST
-- import           Data.Array.MArray
-- import           Data.Array.Unsafe
import           Data.Ix
import           Data.Maybe
-- import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
-- import           Data.Graph
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntSet (IntSet)
-- import qualified Data.IntSet as IntSet
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR(..), ViewL(..), Seq)
-- import qualified Data.Sequence              as Seq
-- import           Data.Foldable (toList, minimumBy)
import           Debug.Trace

data Deque = Q ![Int] !Int ![Int] !Int deriving (Show)

emptyQ :: Deque
emptyQ = Q [] 0 [] 0

viewQ :: Deque -> [Int]
viewQ (Q xs _ ys _) = xs ++ reverse ys

insertQ :: Int -> Deque -> Deque
insertQ a (Q x lx y ly) = chk $! Q (a:x) (lx + 1) y ly

deleteQ :: Int -> Deque -> Deque
deleteQ a (Q x lx y ly)
  | a `elem` x = chk $! Q (delete a x) (lx - 1) y ly
  | a `elem` y = chk $! Q x lx (reverse $ delete a (reverse y)) (ly - 1)
  | otherwise = chk $! Q x lx y ly

deleteFirstQ :: Deque -> Deque
deleteFirstQ (Q (_:xs) lx y ly) = chk $! Q xs (lx - 1) y ly
deleteFirstQ (Q [] _ [_] _) = chk emptyQ

deleteLastQ :: Deque -> Deque
deleteLastQ (Q x lx (_:ys) ly) = chk $! Q x lx ys (ly - 1)

chk :: Deque -> Deque
chk (Q [] 0 [] 0) = Q [] 0 [] 0
chk (Q [x] 1 [] 0) = Q [] 0 [x] 1
chk (Q x lx y ly)
  | lx > c * ly + 1 = Q x' i y' j
  | ly > c * lx + 1 = Q x'' i y'' j
  | otherwise = Q x lx y ly
  where
    c = 3 -- constant value > 1
    i = (lx + ly) `div` 2
    j = lx + ly - i
    x' = take i x
    y' = y ++ reverse (drop i x)
    x'' = x ++ reverse (drop i y)
    y'' = take i y

main = do
  n <- readInt1 <$> BS.getLine
  qs <- map BS.words <$> replicateM n BS.getLine
  putIntN $ solve qs

solve = viewQ . foldl' f emptyQ where
  f' q query = traceShowId $ f q query
  f !q (x:xs)
    | x == "insert" = insertQ (readInt1 $ head xs) q
    | x == "delete" = deleteQ (readInt1 $ head xs) q
    | x == "deleteFirst" = deleteFirstQ q
    | x == "deleteLast" = deleteLastQ q

readInt321 :: BS.ByteString -> Int32
readInt321 = fromIntegral . fst . fromJust . BS.readInteger

-- putInt32N :: [Int32] -> IO ()
-- putInt32N [] = return ()
-- putInt32N xs = BL.putStrLn . toLazyByteString . foldl1 mappend . intersperse (char8 ' ') $ map int32Dec xs
putIntN :: [Int] -> IO ()
putIntN = putStrLn . unwords . map show

--  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --

format :: Show a => Maybe a -> IO ()
format Nothing = putStrLn "NO"
format (Just a) = putStrLn "YES" >> print a

-- [1,2,3] -> 1 2 3
-- putIntN :: [Int] -> IO ()
-- putIntN [] = return ()
-- putIntN xs = BL.putStrLn . toLazyByteString . foldl1 mappend . intersperse (char8 ' ') $ map intDec xs

readInt1 :: BS.ByteString -> Int
readInt1 = fst . fromJust . BS.readInt

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readIntN

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readIntN

readIntN :: BS.ByteString -> [Int]
readIntN =  map readInt1 . BS.words

readInt641 :: BS.ByteString -> Int64
readInt641 = fromIntegral . fst . fromJust . BS.readInteger

readInt642 :: BS.ByteString -> (Int64,Int64)
readInt642 = toTuple . readInt64N

readInt643 :: BS.ByteString -> (Int64,Int64,Int64)
readInt643 = toTriple . readInt64N

readInt64N :: BS.ByteString -> [Int64]
readInt64N =  map readInt641 . BS.words

readInteger1 :: BS.ByteString -> Integer
readInteger1 = fst . fromJust . BS.readInteger

readInteger2 :: BS.ByteString -> (Integer,Integer)
readInteger2 = toTuple . readIntegerN

readInteger3 :: BS.ByteString -> (Integer,Integer,Integer)
readInteger3 = toTriple . readIntegerN

readIntegerN :: BS.ByteString -> [Integer]
readIntegerN =  map readInteger1 . BS.words

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

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

fromTuple :: (a, a) -> [a]
fromTuple (x, y) = [x, y]

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

-- if not applying, use "const"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)

-- @since 4.8.0.0
sortOn' :: Ord b => (a -> b) -> [a] -> [a]
sortOn' f =
  map snd . sortBy (comparing fst) . map (\x -> let y = f x in y `seq` (y, x))


import           Control.Applicative
import           Control.Monad
import           Text.Printf

import           Control.Monad.ST
import           Data.STRef

import           Data.Foldable       (toList)
import qualified Data.Sequence       as S

insert :: a -> S.Seq a -> S.Seq a
insert = (S.<|)

delete :: Eq a => a -> S.Seq a -> S.Seq a
delete x s
    | S.null r = s
    | otherwise =
        case S.viewl r of
            x S.:< xs -> l S.>< xs
  where
    (l, r) = S.breakl (== x) s

deleteFirst :: S.Seq a -> S.Seq a
deleteFirst s =
    case S.viewl s of
        x S.:< xs -> xs

deleteLast :: S.Seq a -> S.Seq a
deleteLast s =
    case S.viewr s of
        xs S.:> x -> xs

doCommands :: [[String]] -> [Int]
doCommands css =
    toList $
    runST $ do
        s <- newSTRef (S.empty)
        forM_ css $ \cs -> do
            case cs of
                ["insert", n]   -> modifySTRef' s (insert (read n))
                ["delete", n]   -> modifySTRef' s (delete (read n))
                ["deleteFirst"] -> modifySTRef' s (deleteFirst)
                ["deleteLast"]  -> modifySTRef' s (deleteLast)
        readSTRef s

main :: IO ()
main = do
    return ()
    n <- readLn
    cs <- fmap words <$> replicateM n getLine
    let answer = doCommands cs
    putStrLn $ unwords $ fmap show answer