--bin search

import Data.Array

--assume that input array was sorted by assending

find::Array Int Int ->Int->(Int,Int)->Bool
find ar x (start,end)  =  let mid = div (start + end) 2 in
                          if (ar!mid) < x then find ar x (mid ,end ) else
                          if (ar!mid) > x then find ar x (start,mid) else
                          if (ar!mid ==x) || (ar!start ==x) || (ar!end ==x) then True else False

--first
solver::Array Int Int -> [Int] -> Int
solver s t = sum (map (\ x -> if find s x (bounds s) then 1 else 0) t)

main::IO()
main = do
  nc<-getLine
  let n = read nc
  sc<-getLine
  let s = map read (words sc)::[Int]
  let s_arr = listArray (1,n) s
  _<-getLine
  tc<-getLine
  let t = map read (words tc)::[Int]
  print (solver s_arr t)

Search II

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

Elements in S is sorted in ascending order

n ≤ 100000

q ≤ 50000

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
1 2 3
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


--bin search

import Data.Array

--assume that input array was sorted by assending

find::Array Int Int ->Int->(Int,Int)->Bool
find ar x (start,end)  =  let mid = div (start + end) 2 in
                          if (ar!mid ==x) || (ar!start ==x) || (ar!end ==x) then True else
                          if end - start <=1 then False else
                          if (ar!mid) > x then find ar x (start+1,mid-1) else
                          if (ar!mid) < x then find ar x (mid+1,end-1) else  False

--first
solver::Array Int Int -> [Int] -> Int
solver s t = sum (map (\ x -> if find s x (bounds s) then 1 else 0) t)

main::IO()
main = do
  nc<-getLine
  let n = read nc
  sc<-getLine
  let s = map read (words sc)::[Int]
  let s_arr = listArray (1,n) s
  _<-getLine
  tc<-getLine
  let t = map read (words tc)::[Int]
  print (solver s_arr t)

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

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.List
ans s q = length $ nub $ filter (\x -> elem x s) q

main = do
  getLine
  s' <- getLine
  getLine
  q' <- getLine
  let s = map read $ words s' :: [Int]
      q = map read $ words q' :: [Int]
      o = ans s q
  print o


import Control.Applicative
import Data.List

search sub_ns q = map (\x -> if (sum x) == q then True else False) sub_ns

exsearch :: [Int] -> Int -> IO()
exsearch ns q = do
    let sub_ns = subsequences ns
        sub_ns_res = search sub_ns q
     in if (elem True sub_ns_res) then putStrLn $ "yes" else putStrLn $ "no"

main :: IO ()
main = do
    _n <- getLine
    let n = read _n :: Int
    ns <-  (map (\x -> read x :: Int). words) <$> getLine
    _q <- getLine
    let q = read _q :: Int
    qs <-  (map (\x -> read x :: Int). words) <$> getLine
    mapM_ (exsearch ns) qs

Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given.

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].


import Control.Applicative ((<$>), (<*>))
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Bool (bool)
import Data.List (unfoldr)
import Data.Char (isSpace)

main :: IO ()
main = solve <$> f <*> f >>= mapM_ putStrLn
  where f = B.getLine >> readil B.readInt <$> B.getLine

solve :: [Int] -> [Int] -> [String]
solve as = map (bool "no" "yes" . search as)

search xs m | m == 0 = True
            | m < 0 = False
            | null xs = False
            | otherwise = let (y:ys) = xs
                          in search ys m || search ys (m - y)

readil :: Integral a =>  (ByteString -> Maybe (a, ByteString)) -> ByteString -> [a]
readil f = unfoldr g
  where
    g s = do
      (n, s') <- f s
      return (n, B.dropWhile isSpace s')


import Control.Applicative
import Control.Monad
import Data.Array.IO

main = do
        n <- readLn
        list <- map read.words<$>getLine
        arr <- newListArray (1,n) list
        b <- countingSort 10000 arr
        putStrLn.unwords.map show =<< getElems b

countingSort :: Int -> IOArray Int Int -> IO (IOArray Int Int)
countingSort k arr = do
        countArr <- newArray (0,k) 0 :: IO (IOArray Int Int)
        countFreq countArr arr
        accumulateCount countArr
        writeElems countArr arr
        where
            countFreq :: IOArray Int Int -> IOArray Int Int -> IO ()
            countFreq ca a = do
                (s,g) <- getBounds a
                forM_ [s..g] $ \j -> readArray a j >>= \i -> modifyArray ca i (+1)
            accumulateCount ca = forM_ [1..k] $ \i -> do
                e' <- readArray ca (i-1)
                modifyArray ca i (+e')
            writeElems :: IOArray Int Int -> IOArray Int Int -> IO (IOArray Int Int)
            writeElems ca a = do
                (s,g) <- getBounds a
                b <- newArray_ (s,g)
                forM_ [g,(g-1)..1] $ \j -> do
                    eA <- readArray a j
                    eC <- readArray ca eA
                    writeArray b eC eA
                    modifyArray ca eA (subtract 1)
                return b

modifyArray arr i f = do
        e <- readArray arr i
        writeArray arr i (f e)

Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

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

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5


import Control.Applicative ((<$>))
import Control.Monad (foldM)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B

main :: IO ()
main = do
  B.getLine
  B.lines <$> B.getContents >>= solve

solve :: [ByteString] -> IO ()
solve bs = foldM f Leaf bs >> return ()
  where f :: BSTree Int -> ByteString -> IO (BSTree Int)
        f tr bs = case B.words bs of
                   [_, bn] -> return (bstInsert (readi B.readInt bn) tr)
                   _ -> do
                     printList $ inOrder tr
                     printList $ preOrder tr
                     return tr

data BSTree a = Leaf | Node a (BSTree a) (BSTree a) deriving Show

bstInsert :: (Ord a) => a -> BSTree a -> BSTree a
bstInsert x (Node y lt rt) | x > y = Node y lt (bstInsert x rt)
                           | x < y = Node y (bstInsert x lt) rt
                           | otherwise = Node y lt rt
bstInsert x Leaf = Node x Leaf Leaf

foldPre :: (a -> b -> b) -> b -> BSTree a -> b
foldPre f z Leaf = z
foldPre f z (Node x l r) = f x y2
  where y1 = foldPre f z r
        y2 = foldPre f y1 l

foldIn :: (a -> b -> b) -> b -> BSTree a -> b
foldIn f z Leaf = z
foldIn f z (Node x l r) = foldIn f y2 l
  where y1 = foldIn f z r
        y2 = f x y1

preOrder :: BSTree a -> [a]
preOrder = foldPre (:) []

inOrder :: BSTree a -> [a]
inOrder = foldIn (:) []

printList :: (Show a) => [a] -> IO ()
printList = putStrLn . (' ':) . unwords . map show

readi :: Integral a =>  (ByteString -> Maybe (a, ByteString)) -> ByteString -> a
readi f s = let Just (n, _) = f s in n

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

Binary Search Tree I

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2 y = NIL // parent of x
3 x = 'the root of T'
4 while x ≠ NIL
5 y = x // set the parent
6 if z.key < x.key
7 x = x.left // move to the left child
8 else
9 x = x.right // move to the right child
10 z.p = y
11
12 if y == NIL // T is empty
13 'the root of T' = z
14 else if z.key < y.key
15 y.left = z // z is the left child of y
16 else
17 y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree $T$.

insert $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

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


import Control.Applicative ((<$>))
import Control.Monad (foldM)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B

main :: IO ()
main = map B.words <$> B.lines <$> B.getContents >>= solve

solve :: [[ByteString]] -> IO ()
solve bs = foldM f Leaf bs >> return ()
  where f hp [_, bn] = return $ hpInsert (readi B.readInt bn) hp
        f hp [com] | com == end = return hp
                   | otherwise = do
                       let Just (x, hp') = hpView hp
                       print x
                       return hp'
        end = B.pack "end"

data Heap a = Leaf | Node a (Heap a) (Heap a) deriving Show

hpInsert :: (Ord a) => a -> Heap a -> Heap a
hpInsert x hp = hpMergeBy (flip compare) hp (Node x Leaf Leaf)

hpView :: (Ord a) => Heap a -> Maybe (a, Heap a)
hpView hp = hpViewBy (flip compare) hp

hpMergeBy :: (Ord a) => (a -> a -> Ordering) -> Heap a -> Heap a -> Heap a
hpMergeBy _ Leaf Leaf = Leaf
hpMergeBy _ Leaf hp = hp
hpMergeBy _ hp Leaf = hp
hpMergeBy f (Node x xlt xrt) (Node y ylt yrt) =
  case f x y of
   LT -> Node x (hpMergeBy f xrt (Node y ylt yrt)) xlt
   _ ->  Node y (hpMergeBy f yrt (Node x xlt xrt)) ylt

hpViewBy :: (Ord a) => (a -> a -> Ordering) -> Heap a -> Maybe (a, Heap a)
hpViewBy f Leaf = Nothing
hpViewBy f (Node x xlt xrt) = Just (x, hpMergeBy f xlt xrt)

readi :: Integral a =>  (ByteString -> Maybe (a, ByteString)) -> ByteString -> a
readi f s = let Just (n, _) = f s in n

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

Priority Queue

A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:

$insert(S, k)$: insert an element $k$ into the set $S$

$extractMax(S)$: remove and return the element of $S$ with the largest key

Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$.
The priority queue manages a set of integers, which are also keys for the priority.

Input

Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.

The input ends with "end" operation.

Output

For each "extract" operation, print the element extracted from the priority queue $S$ in a line.

Constraints

The number of operations $\leq 2,000,000$

$0 \leq k \leq 2,000,000,000$

Sample Input 1

insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end

Sample Output 1

8
10
11
2


import Control.Monad
import Text.Printf

main = do
  line <- readline
  let aa = Point { x = line !! 0, y = line !! 1}
  let bb = Point { x = line !! 2, y = line !! 3}
  let l = Line aa bb
  q <- readLn
  input <- replicateM q getLine
  let xs = fmap (fmap (read :: String -> Double) . words) input
  let result = fmap (\e -> (x $ res l (e !! 0) (e !! 1), y $ res l (e !! 0) (e !! 1))) xs
  mapM_  (\r -> (printf "%.8f %.8f\n" (fst r) (snd r))) result
    where res l x1 y1 = l `reflect` Point{x=x1,y=y1}

readline :: (Read a) => IO [a]
readline = fmap (fmap read . words) getLine

eps :: (Floating a) => a
eps = 1e-7

add :: (Ord a, Floating a) => a -> a -> a
add a b
  | abs (a + b) < eps * (abs a + abs b ) = 0.0
  | otherwise = a + b

data Point a = Point { x :: a, y :: a } deriving (Eq)
data Line a = Line {a :: Point a, b :: Point a}

(^+) :: (Ord a, Floating a) => Point a -> Point a -> Point a
a ^+ b =  Point (add (x a) (x b)) (add (y a) (y b))

(^-) :: (Ord a, Floating a) => Point a -> Point a -> Point a
a ^- b = Point (add (x a) (-(x b))) (add (y a) (-(y b)))

(^*) :: (Floating a) => Point a -> a -> Point a
a ^* d = Point (x a * d) (y a * d)

dot :: (Floating a) => Point a -> Point a -> a
a `dot` b = x a * x b + y a * y b

project :: (Ord a, Floating a) => Line a -> Point a -> Point a
l `project` p = a l ^+ (base ^* t)
  where base = b l ^- a l
        t = ((p ^- a l) `dot` base) / (base `dot` base)

reflect :: (Ord a, Floating a) => Line a -> Point a -> Point a
l `reflect` p = p ^+ (((l `project` p) ^- p) ^* 2.0)

Reflection

For given three points p1, p2, p, find the reflection point x of p onto p1p2.

Input

xp1 yp1 xp2 yp2
q
xp0 yp0
xp1 yp1
...
xpq−1 ypq−1

In the first line, integer coordinates of p1 and p2 are given. Then, q queries are given for integer coordinates of p.

Output

For each query, print the coordinate of the reflection point x. The output values should be in a decimal fraction with an error less than 0.00000001.

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xi, yi ≤ 10000

p1 and p2 are not identical.

Sample Input 1

0 0 2 0
3
-1 1
0 1
1 1

Sample Output 1

-1.0000000000 -1.0000000000
0.0000000000 -1.0000000000
1.0000000000 -1.0000000000

Sample Input 2

0 0 3 4
3
2 5
1 4
0 3

Sample Output 2

4.2400000000 3.3200000000
3.5600000000 2.0800000000
2.8800000000 0.8400000000


import Control.Applicative ((<$>))
import Control.Monad
import Data.Complex
import Text.Printf

type Vector = Complex Double

dot :: Vector -> Vector -> Double
dot a b = realPart $ conjugate a * b

normalize :: Vector -> Vector
normalize = signum

readWords :: Read a => IO [a]
readWords = map read . words <$> getLine

main :: IO ()
main = do
  [x1,y1,x2,y2] <- readWords :: IO [Double]
  let
    p1 = x1:+y1
    p2 = x2:+y2
    d = normalize (p2-p1)

  q <- readLn

  ps <- replicateM q $ do
    [x,y] <- readWords :: IO [Double]
    return $ x:+y

  forM_ ps $ \p -> do
    let x:+y = p+(p1+((p-p1)`dot`d:+0)*d-p)*(2:+0)
    printf "%.10f %.10f\n" x y


import Data.IntMap ((!))
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe
import Control.Applicative

untilFix f x = if f x == x then x else untilFix f (f x)

main = do
 [n,q] <- map read . words <$> getLine
 cxys <- map ((\[c,x,y]->(c,(x,y))) . map (fst . fromJust . B.readInt) . B.words) . B.lines <$> B.getContents
 mapM_ print (uft n q cxys)

uft :: Int -> Int -> [(Int,(Int,Int))] -> [Int]
uft n q = reverse . fst . foldl' process ([],(M.fromDistinctAscList (zip [0..n-1] [0..])))

process (lg,m) (c,(x,y))
 | c==0 = (lg, M.insert (untilFix (m!) (max x y)) (untilFix (m!) (min x y)) m)
 | c==1 = ((if v1==v2 then 1 else 0) : lg, m)
 where
  v1 = untilFix (m!) (min x y)
  v2 = untilFix (m!) (max x y)

Disjoint Set

Write a program which manipulates a disjoint set S = {S1, S2, . . . , Sk}.

First of all, the program should read an integer n, then make a disjoint set where each element consists of 0, 1, ... n−1 respectively.

Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of queries for different operations:

unite(x, y): unites sets that contain x and y, say Sx and Sy, into a new set.

same(x, y): determine whether x and y are in the same set.

Input

n q
com1 x1 y1
com2 x2 y2
...
comq xq yq

In the first line, n and q are given. Then, q queries are given where com represents the type of queries. '0' denotes unite and '1' denotes same operation.

Output

For each same operation, print 1 if x and y are in the same set, otherwise 0, in a line.

Constraints

1 ≤ n ≤ 10000

1 ≤ q ≤ 100000

x ≠ y

Sample Input

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

Sample Output

0
0
1
1
1
0
1
1


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

data Tree = E | T Int Tree Tree
inf = 2^31-1
n_ = 2^17

root = T inf root root

val (T x _ _) = x
val E = inf

update (T _ left right) k x l r
    | r - l == 1 = T x E E
    | k < mid =
        let newleft = update left k x l mid
        in T (min (val newleft) (val right)) newleft right
    | otherwise =
        let newright = update right k x mid r
        in T (min (val left) (val newright)) left newright
    where mid = (l + r) `div` 2

query (T val left right) a b l r
    | b <= l || r <= a = inf
    | a <= l && r <= b = val
    | otherwise = min (query left a b l mid) (query right a b mid r)
    where mid = (l + r) `div` 2

solve [] _ = []
solve ([t,x,y]:qs) tree = case t of
    0 -> solve qs (update tree x y 0 n_)
    1 -> (query tree x (y + 1) 0 n_):(solve qs tree)

main = do
    _ <- getLine
    qs <- map (map (fst . fromJust . B.readInt) . B.words) . B.lines <$> B.getContents
    mapM_ print $ solve qs root

Range Minimum Query (RMQ)

Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations:

find(s, t): report the minimum element in as, as+1, . . . ,at.

update(i, x): change ai to x.

Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.

Input

n q
com0 x0 y0
com1 x1 y1
...
comq−1 xq−1 yq−1

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(xi, yi) and '1' denotes find(xi, yi).

Output

For each find operation, print the minimum element.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 0 ≤ xi < n, 0 ≤ yi < 231-1.

If comi is 1, then 0 ≤ xi < n, 0 ≤ yi < n.

Sample Input 1

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

Sample Output 1

1
2

Sample Input 2

1 3
1 0 0
0 0 5
1 0 0

Sample Output 2

2147483647
5


import Control.Applicative
import Control.Monad.State

data SegTree a = Leaf a | Seg Int (SegTree a) a (SegTree a) deriving (Show)
type Query = StateT (SegTree Int) IO ()

main = do
    [n,q] <- map read.words<$>getLine
    let initTree = fromList $ replicate n 0
    evalStateT (rsq q) initTree

rsq :: Int -> Query
rsq 0 = return ()
rsq q = do
    getQuery
    rsq (q-1)

getQuery :: Query
getQuery = do
    [c,x,y] <- liftIO $ map read.words<$>getLine
    case c of
      0 -> add x y
      1 -> getSum x y
      2 -> (get >>= \seg -> lift $ print seg)

add :: Int -> Int -> Query
add i x = modify $ addSeg i x

getSum :: Int -> Int -> Query
getSum s t = get >>= (\seg -> lift . print . getSumSeg (s,t) $ seg)

val :: SegTree a -> a
val (Leaf x) = x
val (Seg _ _ x _) = x

size :: SegTree a -> Int
size (Leaf x) = 1
size (Seg s _ _ _) = s

fromList :: Num a => [a] -> SegTree a
fromList xs = fl n xs
    where n = length xs

fl :: Num a => Int -> [a] -> SegTree a
fl _ [x] = Leaf x
fl n xs = Seg s l v r
    where
        n' = n `div` 2
        (xsL, xsR) = splitAt n' xs
        l = fl n' xsL
        r = fl (n-n') xsR
        v = val l + val r
        s = size l + size r

addSeg :: Num a => Int -> a -> SegTree a -> SegTree a
addSeg _ x (Leaf v) = Leaf (v+x)
addSeg i x (Seg n l v r)
  | i <= n' = Seg n left (val left + val r) r
  | otherwise = Seg n l (val l + val right) right
  where
      n' = n `div` 2
      left = addSeg i x l
      right = addSeg (i - n') x r

getSumSeg :: Num a => (Int, Int) -> SegTree a -> a
getSumSeg _ (Leaf x) = x
getSumSeg (s,t) (Seg n l v r)
  | s == 1 && t == n = v
  | t <= n' = getSumSeg (s,t) l
  | s > n' = getSumSeg (s - n', t - n') r
  | s <= n' && t > n' = lsum + rsum
  where n' = n `div` 2
        lsum = getSumSeg (s,n') l
        rsum = getSumSeg (1,t - n') r

Range Sum Query

Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:

add(i, x): add x to ai.

getSum(s, t): print the sum of as, as+1,...,at.

Note that the initial values of ai (i = 1, 2, . . . , n) are 0.

Input

n q
com1 x1 y1
com2 x2 y2
...
comq xq yq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes add(xi, yi) and '1' denotes getSum(xi, yi).

Output

For each getSum operation, print the sum in a line.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 1 ≤ xi ≤ n, 0 ≤ yi ≤ 1000.

If comi is 1, then 1 ≤ xi ≤ n, 1 ≤ yi ≤ n.

Sample Input 1

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

Sample Output 1

3
2


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Control.Monad.ST
import Control.Monad.State
import Control.Applicative
import Control.Arrow
import Data.List
import Data.Array
import Data.Array.IO
import Data.Maybe
import Data.Bits
import Data.Ord
import Data.Ratio
import Data.Int
import Data.Char
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import Data.Tuple
import Data.Function
import Text.Printf
import Debug.Trace
import Numeric

modifyArray arr i f = readArray arr i >>= \x -> writeArray arr i (f x)

listToTuple2 [a,b] = (a,b)
listToTuple3 [a,b,c] = (a,b,c)
listToTuple4 [a,b,c,d] = (a,b,c,d)
listToTuple5 [a,b,c,d,e] = (a,b,c,d,e)

readIntBS = fst . fromJust . BS.readInt

for = flip map

infixr 1 ?
(?) :: Bool -> (a,a) -> a
(?) b t = (if b then fst else snd) t

main :: IO ()
main = do
  [n,q] <- map read . words <$> getLine :: IO [Int]
  queries <- replicateM q $ map read . words <$> getLine :: IO [[Int]]
  let inf = 2^31-1

  seg <- stToIO $ newLazySegmentTree n 0 :: IO (IOLazySegmentTree Int)

  forM_ queries $ \query -> do
    case query of
      [0,s,t,x] -> stToIO $ modifyLazySegmentTree seg (s-1) t 0 (+x) (+)
      [1,i] -> print =<< (stToIO $ findLazySegmentTree seg (i-1) 0 (+))

  --mapM_ print =<< stToIO (showLazySegmentTree seg 4)

type IOLazySegmentTree a = STLazySegmentTree RealWorld a
type STLazySegmentTree s a = VM.MVector s a

newLazySegmentTree :: Num a => Int -> a -> ST s (STLazySegmentTree s a)
newLazySegmentTree n x = V.thaw $ V.replicate m x
  where m = 2 * (2 ^ (ceiling $ logBase 2 (fromIntegral n))) - 1

modifyLazySegmentTree :: Num a => STLazySegmentTree s a -> Int -> Int -> a -> (a -> a) -> (a -> a -> a) -> ST s ()
modifyLazySegmentTree tree x y e g f = do
  aux 0 0 n
  where
    n = (VM.length tree) `div` 2 + 1
    aux i l r
      | r <= x || y <= l = return ()
      | x <= l && r <= y = propag i >> VM.read tree i >>= \a -> VM.write tree i (g a)
      | otherwise = aux (i*2+1) l ((l+r)`div`2) >> aux (i*2+2) ((l+r)`div`2) r

    propag i = do
      a <- VM.read tree i
      when (i<n-1) $ do
        VM.read tree (i*2+1) >>= \b -> VM.write tree (i*2+1) (f a b)
        VM.read tree (i*2+2) >>= \b -> VM.write tree (i*2+2) (f a b)
        VM.write tree i e

findLazySegmentTree :: Num a => STLazySegmentTree s a -> Int -> a -> (a -> a -> a) -> ST s a
findLazySegmentTree tree i e f = do
  aux ((j-1)`div`2)
  VM.read tree j
  where
    n = (VM.length tree + 1) `div` 2
    j = i + n - 1
    aux x = do
      when (x >= 0) $ do
        aux ((x-1)`div`2)
        propag x

    propag i = do
      a <- VM.read tree i
      when (i < n-1) $ do
        VM.read tree (i*2+1) >>= \b -> VM.write tree (i*2+1) (f a b)
        VM.read tree (i*2+2) >>= \b -> VM.write tree (i*2+2) (f a b)
        VM.write tree i e

showLazySegmentTree :: Show a => STLazySegmentTree s a -> Int -> ST s [String]
showLazySegmentTree tree len = do
  let
    n = (VM.length tree) `div` 2 + 1
    xs = init $ scanl (+) 0 (takeWhile (<=n) (iterate (*2) 1))
    ys = reverse xs

  forM (zip xs ys) $ \(s,s') -> do
    concat <$> (forM [s..s*2] $ \i -> (\str -> "[" ++ (take' (len * (n `div` (s+1)) + s'*2) str) ++ "]") . show <$> VM.read tree i)

  where
    take' n xs = if length t <= n then t ++ (replicate (n - length t) ' ') else t
      where t = take n xs

Range Add Query (RAQ)

Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:

add(s, t, x): add x to as, as+1, ..., at.

get(i): output the value of ai.

Note that the initial values of ai (i = 1, 2, . . . , n) are 0.

Input

n q
query1
query2
:
queryq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:

0 s t x

or

1 t

The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes get(i).

Output

For each get operation, print the value.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

1 ≤ s ≤ t ≤ n

1 ≤ i ≤ n

0 ≤ x ≤ 1000

Sample Input 1

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

Sample Output 1

3
5

Sample Input 2

4 3
1 2
0 1 4 1
1 2

Sample Output 2

0
1


import Data.IntMap ((!))
import qualified Data.IntMap as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Applicative
import Data.Maybe
import Data.List

type Weight = Int
type Vertex = Int

type PriorityQueue = S.Set (Weight, Vertex)
nullq = S.null
empty = S.empty
push c v = S.insert (c,v)
pop = S.deleteFindMin

readEdge = (\[s,t,d] -> (s,[(t,d)])) . map (fst . fromJust . B.readInt) . B.words

main = do
 [nv,ne,v0] <- map read . words <$> getLine
 es <- sort . map readEdge . B.lines <$> B.getContents
 let g = foldr (\(k,v) acc -> M.insertWith (flip (++)) k v acc) M.empty es
 mapM_ (putStrLn . maybe "INF" show . sumOfWeight g nv ne v0 es) [0..nv-1]

sumOfWeight g nv ne v0 es v = M.lookup v imr
 where
  (imr,_) = until (nullq . snd) (dijkstra g) (im0,q0)
  im0 = M.singleton v0 0
  q0 = push 0 v0 S.empty

dijkstra g (im,q) = (im',q'')
 where
  ((d,v),q') = pop q
  im' = foldl' (\acc (b,c) -> M.insertWith min b (d+c) acc) im vns
  q'' = foldl' (\acc (b,c) -> push (d+c) b acc) q' vns
  vns = filter (\(b,c) -> M.notMember b im || d+c < M.findWithDefault 0 b im) (M.findWithDefault [] v g)

Single Source Shortest Path

For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).

Input

An edge-weighted graph G (V, E) and the source r.

|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.

si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.

Output

Print the costs of SSSP in the following format.

c0
c1
:
c|V|-1

The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.

Constraints

1 ≤ |V| ≤ 100000

0 ≤ di ≤ 10000

0 ≤ |E| ≤ 500000

There are no parallel edges

There are no self-loops

Sample Input 1

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

Sample Output 1

0
1
3
4

Sample Input 2

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

Sample Output 2

3
0
2
INF


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE FlexibleContexts #-}
module Main (main) where
import Data.List
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import Control.Monad
import Data.Maybe
import Debug.Trace
import Data.Vector ((!))
import Control.Applicative
getInts :: IO [Int]
getInts = unfoldr (B8.readInt . B8.dropWhile (==' ')) <$> BS.getLine
data Edge = Edge {to :: !Int,revIx :: !Int,capIx :: !Int}
  deriving (Show,Eq)
type Graph = V.Vector (V.Vector Edge)

printGraph :: Show a => V.Vector (V.Vector a) -> IO ()
printGraph = V.mapM_ (\i -> V.mapM (putStr . (' ':) . show) i >> putStrLn "")

printCap :: MV.IOVector Int -> IO ()
printCap v = print =<< V.freeze v

getGraph :: IO (Graph,MV.IOVector Int)
getGraph = do
  v:e:_ <- getInts
  cap <- MV.new (e*2)
  g <- MV.replicate v []
  forM_ [0..e-1] $ \i -> do
    u:v:c:_ <- getInts
    MV.write cap i c
    MV.write cap (i + e) 0
    us <- MV.read g u
    vs <- MV.read g v
    MV.write g u $ Edge v (e+i) i: us
    MV.write g v $ Edge u i (e+i): vs
    return ()
  g' <- V.map (V.fromList . reverse) <$> V.freeze g
  return (g', cap)

main :: IO ()
main = do
  (g,cap) <- getGraph
  -- printGraph g
  -- printCap cap
  r <- maxFlow 0 (V.length g - 1) g cap
  print r
  return ()

untilJustM :: Monad m => (a -> m (Maybe b)) -> V.Vector a -> m (Maybe b)
untilJustM act xs
  | V.null xs = return Nothing
  | otherwise = let v = V.head xs
                in do
      x <- act v
      case x of
        Nothing -> untilJustM act (V.tail xs)
        Just _ -> return x

maxFlow :: Int -> Int -> Graph -> MV.IOVector Int -> IO Int
maxFlow s t g cap = loop 0
  where
    loop f = do
      used <- MV.replicate (V.length g) False
      df <- dfs maxBound s t g cap used
      if df == 0
        then return f
        else loop (f + df)

dfs :: Int -> Int -> Int -> Graph
  -> MV.IOVector Int
  -> MV.IOVector Bool
  -> IO Int
dfs f v t g cap used
  -- | traceShow v False = undefined
  | v == t = return f
  | otherwise = do
      MV.write used v True
      fromMaybe 0 <$> untilJustM act (g ! v)
  where
    act :: Edge -> IO (Maybe Int)
    act e@Edge {to = to,capIx = ci, revIx = ri} = do
      c <- MV.read cap ci
      isUsed <- MV.read used to
      if c > 0 && not isUsed
      then do
        d <- dfs (min f c) to t g cap used
        if d > 0
        then do
          modifyCap cap e d
          return (Just d)
        else return Nothing
      else return Nothing

modifyCap :: MV.IOVector Int -> Edge -> Int -> IO ()
modifyCap cap Edge {capIx = ci, revIx = ri} d
  = do
  cv <- MV.read cap ci
  cr <- MV.read cap ri
  MV.write cap ci $ cv - d
  MV.write cap ri $ cr + d

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

Maximum Flow

A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$.

Input

A flow network is given in the following format.

$|V|\;|E|$

$u_0\;v_0\;c_0$

$u_1\;v_1\;c_1$

:

$u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$

$|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$.

$u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network.
A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge.

Output

Print the maximum flow.

Constraints

$2 \leq |V| \leq 100$

$1 \leq |E| \leq 1000$

$0 \leq c_i \leq 10000$

Sample Input 1

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

Sample Output 1

3


import Control.Applicative
import Data.List
main = do
  cs <- map (sort . map read . words) . lines <$> getContents :: IO [[Int]]
  mapM (putStrLn . unwords . map show) $ init cs

Swapping Two Numbers

Write a program which reads two integers x and y, and prints them in ascending order.

Input

The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.

The input ends with two 0 (when both x and y are zero). Your program should not process for these terminal symbols.

Output

For each dataset, print x and y in ascending order in a line. Put a single space between x and y.

Constraints

0 ≤ x, y ≤ 10000

the number of datasets ≤ 3000

Sample Input

3 2
2 2
5 3
0 0

Sample Output

2 3
2 2
3 5


import Control.Applicative

swap [x,y] | x > y = [y,x]
swap [x,y]         = [x,y]

main = do
    ss <- words <$>getLine
    let x:y:_ = swap $ take 2 [ read s | s <- ss]

    if x+y>0 then do
      putStrLn $ show x ++ " " ++ show y
      main
    else return()


import qualified Data.List.Split as S

main :: IO()
main = do
    d <- readDatas
    case d of
        ("0","0") -> return ()
        otherwise -> (tuplePrint $ sort d) >> main

tuplePrint :: (String,String) -> IO()
tuplePrint (a,b) = putStrLn $ a ++ ' ':b

readDatas :: IO ((String,String))
readDatas = do
    l <- getLine
    let (a:b:_) = S.splitOn " " l
    return $ (a,b)

sort :: (String,String) ->  (String,String)
sort (a,b)
    | an > bn = (b,a)
    | otherwise = (a,b)
    where
        an = read a :: Integer
        bn = read b :: Integer


import Data.Functor( (<$>))
import Data.List( sort)
import Control.Monad( forM_)

main = do
    inputs <- takeWhile ("0 0"/=) . lines <$> getContents
    let
	processPerLine line = sort $ (read::String->Int) <$> (words line)
	putStrLn4itp0103c [small,big]
	  =
	    putStrLn $ (show small)++" "++(show big)

    forM_ inputs $
	    putStrLn4itp0103c . processPerLine


module Main where

import Control.Applicative
import Text.Printf
import Numeric

main :: IO()
main = do
  { _ <- getLine
  ; xs <- getInts
  ; let mx = maximum xs
  ; let mn = minimum xs
  ; let sm = sum xs
  ; putInts [mn, mx, sm]
  }

--

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

putInts :: [Int] -> IO()
putInts = putStrLn . unwords. map show

getDoubles :: IO[Double]
getDoubles = map read. words <$> getLine

putDoubles :: [Double] -> IO ()
putDoubles = putStrLn . unwords . map showDouble

showDouble :: Double -> String
showDouble x = showFFloat Nothing x ""

getStrings :: IO [String]
getStrings = words <$> getLine

readInt' :: String -> Int
readInt' = read

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

Min, Max and Sum

Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.

Input

In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in a line.

Output

Print the minimum value, maximum value and sum in a line. Put a single space between the values.

Constraints

$0 < n \leq 10000$

$-1000000 \leq a_i \leq 1000000$

Sample Input

5
10 1 5 4 17

Sample Output

1 17 37


import Control.Monad
import Control.Applicative
mMulV m v = map calcEachLine m where
    calcEachLine l = sum $ zipWith (*) l v
main = do
    [n,m] <- map read . words <$> getLine
    matrix <- replicateM n $ map (read :: String->Int) . words <$> getLine :: IO [[Int]]
    vector <- replicateM m $ (read :: String->Int) <$> getLine :: IO [Int]
    mapM_ print $ mMulV matrix vector

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

Matrix Vector Multiplication

Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.

A column vector with m elements is represented by the following equation.

\[
b = \left(
\begin{array}{c}
b_1 \\
b_2 \\
: \\
b_m \\
\end{array}
\right)
\]

A $n \times m$ matrix with $m$ column vectors, each of which consists of $n$ elements, is represented by the following equation.

\[
A = \left(
\begin{array}{cccc}
a_{11} & a_{12} & ... & a_{1m} \\
a_{21} & a_{22} & ... & a_{2m} \\
: & : & : & : \\
a_{n1} & a_{n2} & ... & a_{nm} \\
\end{array}
\right)
\]

$i$-th element of a $m \times 1$ column vector $b$ is represented by $b_i$ ($i = 1, 2, ..., m$), and the element in $i$-th row and $j$-th column of a matrix $A$ is represented by $a_{ij}$ ($i = 1, 2, ..., n,$ $j = 1, 2, ..., m$).

The product of a $n \times m$ matrix $A$ and a $m \times 1$ column vector $b$ is a $n \times 1$ column vector $c$, and $c_i$ is obtained by the following formula:

\[
c_i = \sum_{j=1}^m a_{ij}b_j = a_{i1}b_1 + a_{i2}b_2 + ... + a_{im}b_m
\]

Input

In the first line, two integers $n$ and $m$ are given. In the following $n$ lines, $a_{ij}$ are given separated by a single space character. In the next $m$ lines, $b_i$ is given in a line.

Output

The output consists of $n$ lines. Print $c_i$ in a line.

Constraints

$1 \leq n, m \leq 100$

$0 \leq b_i, a_{ij} \leq 1000$

Sample Input

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

Sample Output

5
6
9


import Control.Monad
import Control.Applicative
readDigits = map read <$> words <$> getLine :: IO [Int]
main = do
    [n,m] <- readDigits
    matrix <- replicateM n $ readDigits
    vector <- replicateM m $ readLn :: IO [Int]
    putStr $ unlines [show . sum $ zipWith (*) m vector | m<-matrix]


import Control.Monad
import Control.Applicative

ways n x = let allComb = [(a,b,c) | a <- [1..n], b <- [1..n], c <- [1..n], a < b && b < c] in
    length $ filter (\(l,m,n)->l+m+n == x) allComb

processInputLine [n,x] =
    if n == 0 && x == 0 then return () else print $ ways n x

main = do
    mapM_ processInputLine =<< map (map (read :: String->Int) . words) <$> lines <$> getContents

How many ways?

Write a program which identifies the number of combinations of three integers which satisfy the following conditions:

You should select three distinct integers from 1 to n.

A total sum of the three integers is x.

For example, there are two combinations for n = 5 and x = 9.

1 + 3 + 5 = 9

2 + 3 + 4 = 9

Input

The input consists of multiple datasets. For each dataset, two integers n and x are given in a line.

The input ends with two zeros for n and x respectively. Your program should not process for these terminal symbols.

Constraints

3 ≤ n ≤ 100

0 ≤ x ≤ 300

Output

For each dataset, print the number of combinations in a line.

Sample Input

5 9
0 0

Sample Output

2

Note

      解説


import Control.Monad
import Control.Applicative

combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = []
combinations n (x:xs) = (map (x:) (combinations (n-1) xs)) ++ (combinations n xs)

solve :: [Int] -> String
solve [n, x] =
   show $ length [nc3 | nc3<-combinations 3 [1..n], sum nc3==x]

main =
    mapM_ putStrLn =<< map solve . takeInputs . lines <$> getContents
    where
    takeInputs :: [String] -> [[Int]]
    takeInputs = takeWhile (not . all (== 0)) . map (map read . words)


module Main where

import Control.Applicative
import Numeric
import Data.List (transpose)

main :: IO ()
main = do
  {[r, c] <- getInts
  ; mat <- loop r
  ; mapM_  putInts (autoSum mat)
  }

loop :: Int -> IO [[Int]]
loop 0 = return []
loop r = do
  { xs <- getInts
  ; xss <- loop (r-1)
  ; return (xs : xss)
  }

autoSum :: [[Int]] -> [[Int]]
autoSum = transpose  .  map addSum . transpose . map addSum

addSum :: [Int] -> [Int]
addSum xs = xs ++ [sum xs]

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

putInts :: [Int] -> IO ()
putInts = putStrLn .  unwords . map show

getDoubles :: IO [Double]
getDoubles = map read . words <$> getLine

putDoubles :: [Double] -> IO ()
putDoubles = putStrLn . unwords . map showDouble

showDouble :: Double -> String
showDouble d = showFFloat Nothing d ""

Spreadsheet

Your task is to perform a simple table calculation.

Write a program which reads the number of rows r, columns c and a table of r × c elements, and prints a new table, which includes the total sum for each row and column.

Input

In the first line, two integers r and c are given. Next, the table is given by r lines, each of which consists of c integers separated by space characters.

Output

Print the new table of (r+1) × (c+1) elements. Put a single space character between adjacent elements. For each row, print the sum of it's elements in the last column. For each column, print the sum of it's elements in the last row. Print the total sum of the elements at the bottom right corner of the table.

Constraints

1 ≤ r, c ≤ 100

0 ≤ an element of the table ≤ 100

Sample Input

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

Sample Output

1 1 3 4 5 14
2 2 2 4 5 15
3 3 0 1 1 8
2 3 4 4 6 19
8 9 9 13 17 56


module Main where

import Control.Applicative
import Numeric
import Data.List (transpose)

main :: IO ()
main = do
  { [r, c] <- getInts
  ; mat <- loop r
  ; mapM_ putInts (hoge mat)
  }

loop :: Int -> IO [[Int]]
loop 0 = return []
loop r = do
  { xs <- getInts
  ; xss <- loop (r-1)
  ; return (xs : xss)
  }

hoge :: [[Int]] -> [[Int]]
hoge = transpose . map addSum . transpose . map addSum

addSum :: [Int] -> [Int]
addSum xs = xs ++ [sum xs]

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

putInts :: [Int] -> IO ()
putInts = putStrLn . unwords .  map show

getDoubles :: IO [Double]
getDoubles = map read . words <$> getLine

putDoubles :: [Double] -> IO ()
putDoubles = putStrLn . unwords . map showDouble

showDouble :: Double -> String
showDouble d = showFFloat Nothing d ""


--Structured Program II - Spreadsheet

import Control.Applicative
import Data.List (transpose)

main :: IO ()
main = do
  [r, _] <- map read . words <$> getLine
  xs <- take r . map (map read . words) . lines <$> getContents
  mapM_ (putStrLn . unwords . map show) $ spreadSheet xs

spreadSheet :: [[Int]] -> [[Int]]
spreadSheet xs = (f . f) xs
  where f xs = map (\x -> x ++ [sum x]) $ transpose xs


import Control.Applicative

type Row = [Int]

type Rows = [Row]

type Matrix = (Int, Int, Rows)

type Problem = (Matrix, Matrix)

type Result = Rows

access :: Rows -> Int -> Int -> Int

access rows row col
    = rows !! row !! col

calcElement :: Matrix -> Matrix -> Int -> Int -> Int

calcElement (_, m, rows1) (_, _, rows2) row col
    = sum [access rows1 row x * access rows2 x col | x <- ms] where
        ms = [0..(m - 1)]

solve :: Problem -> Result

solve (mat1@(n, _, _), mat2@(_, l, _))
    = [[calcElement mat1 mat2 row col | col <- ls] | row <- ns] where
        ns = [0..(n - 1)]
        ls = [0..(l - 1)]

output :: Result -> String

output rows
    = init.concat $ [outputRow row ++ "\n" | row <- rows]

outputRow :: Row -> String

outputRow row
    = init.concat $ [show x ++ " " | x <- row]

input :: IO Problem

input
    = do
        [n, m, l] <- map read.words <$> getLine
        rows1 <- inputRows n []
        rows2 <- inputRows m []
        return ((n, m, rows1), (m, l, rows2))

inputRows :: Int -> Rows -> IO Rows

inputRows 0 rows
    = return rows

inputRows n rows
    = do
        row <- map read.words <$> getLine
        inputRows (n - 1) $ rows ++ [row]

main :: IO ()

main
    = putStrLn.output =<< solve <$> input

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

Matrix Multiplication

Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:

\[
c_{ij} = \sum_{k=1}^m a_{ik}b_{kj}
\]

where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.

Input

In the first line, three integers $n$, $m$ and $l$ are given separated by space characters

In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.

Output

Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.

Constraints

$1 \leq n, m, l \leq 100$

$0 \leq a_{ij}, b_{ij} \leq 10000$

Sample Input

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

Sample Output

1 8 5
0 9 6
4 23 14

Note

      解説


sumDigit 0 = 0
sumDigit n = (n`mod`10) + (sumDigit (n`div`10))
main = do{
    getContents >>= mapM_ putStrLn . map (show . sumDigit . (read::String->Int)) . init . lines;
}

Sum of Numbers

Write a program which reads an integer and prints sum of its digits.

Input

The input consists of multiple datasets. For each dataset, an integer x is given in a line. The number of digits in x does not exceed 1000.

The input ends with a line including single zero. Your program should not process for this terminal symbol.

Output

For each dataset, print the sum of digits in x.

Sample Input

123
55
1000
0

Sample Output

6
10
1


import Control.Applicative
main = do{
    [a,b] <- map (read::String->Integer) . words <$> getLine;
    putStrLn $ show $ (a`mod`1000000007)^b`mod`1000000007;
}

Power

For given integers m and n, compute mn (mod 1,000,000,007). Here, A (mod M) is the remainder when A is divided by M.

Input

m n

Two integers m and n are given in a line.

Output

Print mn (mod 1,000,000,007) in a line.

Constraints

1 ≤ m ≤ 100

1 ≤ n ≤ 109

Sample Input 1

2 3

Sample Output 1

8

Sample Input 2

5 8

Sample Output 2

390625


import Control.Applicative

func a 0 = 1
func a b = (a * (func a (b-1))`mod`1000000007)

main = do{
    [a,b] <- map (read::String->Integer) . words <$> getLine;
    putStrLn $ show $ func a b;
}


import Control.Applicative
main = do
 [a,b] <- map read . words <$> getLine
 putStrLn $ unwords [show (a * b)]

Multiplication of Big Integers II

Given two integers $A$ and $B$, compute the product, $A \times B$.

Input

Two integers $A$ and $B$ separated by a space character are given in a line.

Output

Print the product in a line.

Constraints

$-1 \times 10^{200000} \leq A, B \leq 10^{200000}$

Sample Input 1

5 8

Sample Output 1

40

Sample Input 2

100 25

Sample Output 2

2500

Sample Input 3

-1 0

Sample Output 3

0

Sample Input 4

12 -3

Sample Output 4

-36


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TypeFamilies #-}

module Main where

import           Control.Monad
import           Control.Monad.Extra
import           Control.Monad.Primitive
import qualified Data.Array as A
import qualified Data.Array.IO as AIO
import qualified Data.Array.Unboxed as AU
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC8
import           Data.Char
import           Data.Either
import           Data.Function
import qualified Data.Graph.Inductive.Graph as G
import qualified Data.Graph.Inductive.PatriciaTree as G
import qualified Data.Heap as H
import           Data.Int
import           Data.List
import qualified Data.Map.Strict as M
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup
import qualified Data.Sequence as SQ
import qualified Data.Set as S
import           Data.Time
import           Data.Tuple
import qualified Data.Vector as V
import           Data.Vector.Algorithms.Search
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Unboxing as VUG
import qualified Data.Vector.Unboxing.Mutable as VUGM
import           Debug.Trace
import           GHC.Stack

main :: IO ()
main = do
  --aN       <- getI
  --[aA, aB] <- getIL
  --aS       <- getLine
  aK <- getI
  putStrLn $ concat $ replicate aK "ACL"
  return ()

--雑多系
t :: Int -> (Int, Int)
t x = (x, 1)

i def f t = bool t def $ f t

shiftRCnt k = shiftRCntP k 1

shiftRCntP k c = let nk = shiftR k 1
                 in if nk == 0
                    then c
                    else shiftRCntP nk (c + 1)

myVUmap f vu =
  if vu == VU.empty
  then VU.empty
  else VU.unfoldr
    (\x -> let ret = f $ VU.head x
               tailx = VU.tail x
           in if x == VU.empty
              then Nothing
              else if isLeft ret
                   then Just (either id id ret, tailx)
                   else Just (either id id ret, VU.empty))
    vu

myVUmapM f vu =
  if vu == VU.empty
  then return VU.empty
  else VU.unfoldrM
    (\x -> do
       ret <- f $ VU.head x
       let tailx = VU.tail x
       if x == VU.empty
         then return Nothing
         else if isLeft ret
              then return $ Just (either id id ret, tailx)
              else return $ Just (either id id ret, VU.empty))
    vu

myVUmapM_ f vu =
  if vu == VU.empty
  then return ()
  else do
    ret1 <- VU.unfoldrM
      (\x -> do
         ret2 <- f $ VU.head x
         let tailx = VU.tail x
         if x == VU.empty
           then return Nothing
           else if isLeft ret2
                then return $ Just (either id id ret2, tailx)
                else return $ Just (either id id ret2, VU.empty))
      vu
    return ()

myVUfor vu f = myVUmap f vu

myVUforM vu f = myVUmapM f vu

myVUforM_ vu f = myVUmapM_ f vu

myVUfoldl f acc vu =
  if vu == VU.empty
  then return acc
  else do
    let ret = f acc (VU.head vu)
    if isLeft ret
      then myVUfoldl f (either id id ret) (VU.tail vu)
      else return $ either id id ret

myVUfoldr f acc vu =
  if vu == VU.empty
  then return acc
  else do
    let ret = f acc (VU.last vu)
    if isLeft ret
      then myVUfoldr f (either id id ret) (VU.init vu)
      else return $ either id id ret

myVUfoldM f acc vu =
  if vu == VU.empty
  then return acc
  else do
    ret <- f acc (VU.head vu)
    if isLeft ret
      then myVUfoldM f (either id id ret) (VU.tail vu)
      else return $ either id id ret

--周りのマス
aroundSquare y x h w = VU.concatMap
  (\a -> VU.mapMaybe
     (\b -> let ya = y + a
                xb = x + b
            in if abs a + abs b == 1
               then if ya < 0 || ya >= h || xb < 0 || xb >= w
                    then Nothing
                    else Just (ya, xb)
               else Nothing)
   $ VU.enumFromN (-1) 3)
  $ VU.enumFromN (-1) 3

--入力系
splitReadBSC8 :: BSC8.ByteString -> [Int]
splitReadBSC8 bs = let (bs1, newBs) = BSC8.splitAt 1 bs
                   in if newBs == BSC8.empty
                      then [test $ BSC8.readInt bs1]
                      else test (BSC8.readInt bs1):splitReadBSC8 newBs
  where
    test (Just (i, _)) = i

read2DimChar :: VM.IOVector (VUM.IOVector Char) -> Int -> Int -> IO Char
read2DimChar vec y x = do
  vecY <- VM.read vec y
  VUM.read vecY x

write2DimChar :: VM.IOVector (VUM.IOVector Char) -> Int -> Int -> Char -> IO ()
write2DimChar vec y x t = do
  vecY <- VM.read vec y
  VUM.write vecY x t

readTwoDimVec :: VM.IOVector (VUM.IOVector Int) -> Int -> Int -> IO Int
readTwoDimVec vec y x = do
  vecY <- VM.read vec y
  VUM.read vecY x

writeTwoDimVec :: VM.IOVector (VUM.IOVector Int) -> Int -> Int -> Int -> IO ()
writeTwoDimVec vec y x t = do
  vecY <- VM.read vec y
  VUM.write vecY x t

getVUI :: IO (VU.Vector Int)
getVUI = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine

getRepVUI :: Int -> IO (VU.Vector Int)
getRepVUI n = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) . BSC8.unlines
  <$> replicateM n BSC8.getLine

getVS :: IO (V.Vector Char)
getVS = V.fromList <$> getLine

getVUC :: IO (VU.Vector Char)
getVUC = VU.fromList <$> getLine

readI :: BSC8.ByteString -> Int
readI = fst . fromJust . BSC8.readInt

readInteger :: BSC8.ByteString -> Integer
readInteger = fst . fromJust . BSC8.readInteger

readIL :: BSC8.ByteString -> [Int]
readIL = map readI . BSC8.words

readIT2 :: BSC8.ByteString -> (Int, Int)
readIT2 bs = let words = BSC8.words bs
             in (readI $ head words, readI $ last words)

readIT3 :: BSC8.ByteString -> (Int, Int, Int)
readIT3 bs = let words = BSC8.words bs
             in (readI $ head words, readI $ words !! 1, readI $ words !! 2)

getI :: IO Int
getI = readI <$> BSC8.getLine

getInteger :: IO Integer
getInteger = readInteger <$> BSC8.getLine

getIL :: IO [Int]
getIL = readIL <$> BSC8.getLine

getIT2 :: IO (Int, Int)
getIT2 = readIT2 <$> BSC8.getLine

getIT3 :: IO (Int, Int, Int)
getIT3 = readIT3 <$> BSC8.getLine

getIT2Order :: IO (Int, Int)
getIT2Order = getIL
  >>= \x@[xz, xo] -> if xz > xo
                     then return (xo, xz)
                     else return (xz, xo)

getNIS :: Int -> IO [(Int, BSC8.ByteString)]
getNIS 0 = return []
getNIS n = do
  [aFst, aSnd] <- BSC8.words <$> BSC8.getLine
  next <- getNIS (n - 1)
  return ((readI aFst, aSnd):next)

il2Words :: [Int] -> String
il2Words = unwords . map show

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

Score : 100 points

Problem Statement

You are given an integer K.
Print the string obtained by repeating the string ACL K times and concatenating them.

For example, if K = 3, print ACLACLACL.

Constraints

1 \leq K \leq 5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the string obtained by repeating the string ACL K times and concatenating them.

Sample Input 1

3

Sample Output 1

ACLACLACL


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

deleteList [] re = re
deleteList (a:s) re = deleteList s (S.delete a re)

solve [] re = re
solve (ab:abs) re =solve abs (deleteList ab re)

main = do
    [n,m] <- map read . words <$> getLine :: IO [Int]
    abss <- replicateM m (map read . words <$> getLine) :: IO [[Int]]
    print $ S.size $ solve abss (S.fromList $ [1..n])

Score : 300 points

Problem Statement

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M.
Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

2 \leq N \leq 100,000

1 \leq M \leq 100,000

1 \leq A_i < B_i \leq N

No two roads connect the same pair of cities.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Sample Input 1

3 1
1 2

Sample Output 1

1

Initially, there are three cities, and there is a road between City 1 and City 2.

Snuke can achieve the goal by building one new road, for example, between City 1 and City 3.
After that,

We can travel between 1 and 2 directly.

We can travel between 1 and 3 directly.

We can travel between 2 and 3 by following both roads (2 - 1 - 3).


main = do
    s <- getLine
    let l = last s
    let las | l == 's' = "es"
            | otherwise = "s"
    putStr s
    putStrLn las

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


import Data.List

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

solve :: String -> String
solve str | isSuffixOf "s" str == True = str ++ "es"
          | otherwise                  = str ++ "s"


main = do
  s <- getLine
  if last s == 's'
    then putStrLn $ s ++ "es"
    else putStrLn $ s ++ "s"


{-# LANGUAGE BangPatterns #-}
import           Control.Exception           (assert)
import           Control.Monad
import           Control.Monad.Primitive
import qualified Control.Monad.ST            as ST
import qualified Data.Array.IO               as IO
import qualified Data.Array.ST               as ST
import qualified Data.Array.Unboxed          as A
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Foldable
import           Data.List
import qualified Data.Map.Strict             as Map
import           Data.Maybe
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as Set
import qualified Data.Vector                 as VB
import qualified Data.Vector.Mutable         as VBM
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as VM
import           Debug.Trace

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine
getIntVec n = V.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

readInteger = fst . fromJust . BS.readInteger
readIntegerList = map readInteger . BS.words
getInteger = readInteger <$> BS.getLine
getIntegerList = readIntegerList <$> BS.getLine

inf :: Int
inf = 10^18

main = do
  s <- getLine
  let s' = if last s == 's'
        then s ++ "es"
        else s ++ "s"
  putStrLn s'


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

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

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

import qualified Data.ByteString.Char8 as B

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

import Debug.Trace
import Text.Printf

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

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

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

printList [a] = print a
printList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as

main = readInt >>= flip replicateM readInts >>= putStrLn . which "Yes" "No" . ( 3 <= ) . foldl max 0 . map length . filter ( head ) . group . map ( uncurry (==) . mp )

Score : 200 points

Problem Statement

Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.

Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

Constraints

3 \leq N \leq 100

1\leq D_{i,j} \leq 6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

Output

Print Yes if doublets occurred at least three times in a row. Print No otherwise.

Sample Input 1

5
1 2
6 6
4 4
3 3
3 2

Sample Output 1

Yes

From the second roll to the fourth roll, three doublets occurred in a row.

Sample Input 2

5
1 1
2 2
3 4
5 5
6 6

Sample Output 2

No

Sample Input 3

6
1 1
2 2
3 3
4 4
5 5
6 6

Sample Output 3

Yes


module Main where
import qualified Control.Monad as C
import qualified Data.Char as C
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Array as A

int = read :: String -> Int
getWord :: IO String
getWord = do
  c <- getChar
  if C.isSpace c
  then
    return []
  else do
    ws <- getWord
    return (c:ws)
getInt = fmap int getWord
replace pred a = map (\x -> if pred x then a else x)

main = interact $ printer . solver . parser
parser = int
printer = unlines . (:[]) . show

solver n = sum $ map (pattern n) [1..n]

pattern n a = (n-1) `div` a

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.Ord

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    n <- getInt
    as <- getIntList
    bs <- getIntList
    let ga = map (pred . length) . group . sort $ [1..n] ++ as
        gb = map (pred . length) . group . sort $ [1..n] ++ bs
        p = any (> n) $ zipWith (+) ga gb
    let rs = solve ([],[]) as bs
    if p then
        putStrLn "No"
    else do
        putStrLn "Yes"
        putStrLn $ unwords $ map show rs

solve (_,ans) [] [] = reverse ans
solve (l,ans) as [] = solve ([],ans) as l
solve (l,ans) (a:as) (b:bs)
    | a /= b = solve (l,b:ans) as bs
    | a == b = solve (b:l,ans) (a:as) bs

Score : 600 points

Problem Statement

Given are two sequences A and B, both of length N.
A and B are each sorted in the ascending order.
Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.

Constraints

1\leq N \leq 2 \times 10^5

1\leq A_i,B_i \leq N

A and B are each sorted in the ascending order.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N

Output

If there exist no reorderings that satisfy the condition, print No.

If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of B on the second line, separating terms with a whitespace.

If there are multiple reorderings that satisfy the condition, you can print any of them.

Sample Input 1

6
1 1 1 2 2 3
1 1 1 2 2 3

Sample Output 1

Yes
2 2 3 1 1 1

Sample Input 2

3
1 1 2
1 1 3

Sample Output 2

No

Sample Input 3

4
1 1 2 3
1 2 3 3

Sample Output 3

Yes
3 3 1 2


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, BinaryLiterals, CPP, DerivingStrategies  #-}
{-# LANGUAGE DerivingVia, FlexibleContexts, FlexibleInstances       #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, KindSignatures, LambdaCase #-}
{-# LANGUAGE MagicHash, MultiParamTypeClasses, MultiWayIf           #-}
{-# LANGUAGE NumericUnderscores, OverloadedStrings, PatternSynonyms #-}
{-# LANGUAGE RankNTypes, RecordWildCards, ScopedTypeVariables       #-}
{-# LANGUAGE StandaloneDeriving, TupleSections, TypeApplications    #-}
{-# LANGUAGE TypeFamilies, TypeInType, UnboxedTuples, ViewPatterns  #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.Reader
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bifunctor
import           Data.Bool
import qualified Data.ByteString                   as B
import qualified Data.ByteString.Builder           as B
import qualified Data.ByteString.Char8             as C
import qualified Data.ByteString.Internal          as B
import qualified Data.ByteString.Unsafe            as B
import           Data.Char
import qualified Data.Foldable                     as F
import           Data.Function
import           Data.Functor.Identity
import qualified Data.IntMap.Strict                as IM
import qualified Data.IntSet                       as IS
import qualified Data.List                         as L
import qualified Data.Map.Strict                   as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive
import           Data.Proxy
import           Data.Ratio
import           Data.Semigroup
import qualified Data.Set                          as S
import           Data.Tuple
import qualified Data.Vector                       as V
import qualified Data.Vector.Algorithms.Intro      as Intro
import qualified Data.Vector.Fusion.Stream.Monadic as MS
import qualified Data.Vector.Fusion.Bundle.Monadic as MB
import           Data.Vector.Fusion.Util
import qualified Data.Vector.Generic               as G
import qualified Data.Vector.Generic.Mutable       as GM
import qualified Data.Vector.Mutable               as VM
import qualified Data.Vector.Primitive             as P
import qualified Data.Vector.Primitive.Mutable     as PM
import qualified Data.Vector.Unboxed               as U
import qualified Data.Vector.Unboxed.Mutable       as UM
import           Debug.Trace
import           Foreign                           hiding (void)
import           GHC.Exts
import           GHC.TypeLits
import           System.IO
import           Unsafe.Coerce

#define MOD 1000000007

main :: IO ()
main = do
    bs <- C.getLine
    print $ solve bs

solve :: C.ByteString -> Int
solve bs
    = (total -) . U.sum
    . getLCPArray
    . buildLCPArray bs
    $ buildSuffixArray bs
  where
    n = C.length bs
    total = n * (n + 1) `div` 2

newtype SuffixArray = SuffixArray {getSuffixArray :: U.Vector Int} deriving (Show)

getSuffixStartPos :: SuffixArray -> Int -> Int
getSuffixStartPos = U.unsafeIndex . getSuffixArray
{-# INLINE getSuffixStartPos #-}

getSuffix :: SuffixArray -> Int -> B.ByteString -> B.ByteString
getSuffix  = (B.unsafeDrop.) . getSuffixStartPos
{-# INLINE getSuffix #-}

buildSuffixArray :: B.ByteString -> SuffixArray
buildSuffixArray bs = SuffixArray
    . fst
    . F.foldl step (sa0, rank0)
    . takeWhile (<= n)
    $ map (shiftL 1) [0..]
  where
    !n = B.length bs :: Int
    !sa0 = U.generate (n + 1) id
    !rank0 = U.generate n (fromIntegral . B.unsafeIndex bs) `U.snoc` 0
    step (!sa, !rank) k = (sa', rank')
      where
        encode sai =
            let !x = rank U.! sai
                !y | sai + k <= n = rank U.! (sai + k)
                   | otherwise = 0
            in  unsafeShiftL x 40 .|. unsafeShiftL y 20 .|. sai
        maskSA x = x .&. 0xfffff
        maskRank x = unsafeShiftR x 20

        sorted = radixSort64 $ U.map encode sa
        !sa' = U.map maskSA sorted
        !rank' = U.create $ do
            mv <- UM.unsafeNew (n + 1)
            UM.write mv (sa' U.! 0) 1

            U.forM_ (U.zip sorted $ U.tail sorted) $ \(prev, cur) -> do
                x <- UM.unsafeRead mv (maskSA prev)
                UM.unsafeWrite mv (maskSA cur)
                    $ x + fromEnum (maskRank prev < maskRank cur)

            return mv

radixSort64 :: U.Vector Int -> U.Vector Int
radixSort64 v = F.foldl' step v [0, 16, 32, 48]
  where
    mask k x = fromIntegral $ unsafeShiftR x k .&. 0xffff
    step v k = U.create $ do
        pref <- U.unsafeThaw
            . U.prescanl' (+) 0
            . U.unsafeAccumulate (+) (U.replicate 0x10000 0)
            $ U.map (flip (,) 1 . mask k) v
        res <- UM.unsafeNew $ U.length v
        U.forM_ v $ \x -> do
            let !masked = mask k x
            i <- UM.unsafeRead pref masked
            UM.unsafeWrite pref masked $ i + 1
            UM.unsafeWrite res i x
        return res
{-# INLINE radixSort64 #-}

-------------------------------------------------------------------------------
-- Utils
-------------------------------------------------------------------------------
rep :: (Monad m) => Int -> (Int -> m ()) -> m ()
rep n = flip MS.mapM_ (stream 0 n)
{-# INLINE rep #-}
rev :: (Monad m) => Int -> (Int -> m ()) -> m ()
rev !n = flip MS.mapM_ (streamR 0 n)
{-# INLINE rev #-}
stream :: (Monad m) => Int -> Int -> MS.Stream m Int
stream !l !r = MS.Stream step l where { step x | x < r = return $ MS.Yield x (x + 1) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] stream #-}
streamR :: (Monad m) => Int -> Int -> MS.Stream m Int
streamR !l !r = MS.Stream step (r - 1) where { step x | x >= l = return $ MS.Yield x (x - 1) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] streamR #-}
stream' :: (Monad m) => Int -> Int -> Int -> MS.Stream m Int
stream' !l !r !d = MS.Stream step l where { step x | x < r = return $ MS.Yield x (x + d) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] stream' #-}
infixl 8 `shiftRL`, `unsafeShiftRL`
shiftRL :: Int -> Int -> Int
shiftRL = unsafeShiftRL
{-# INLINE shiftRL #-}
unsafeShiftRL :: Int -> Int -> Int
unsafeShiftRL (I# x#) (I# i#) = I# (uncheckedIShiftRL# x# i#)
{-# INLINE unsafeShiftRL #-}
type Parser a = StateT C.ByteString Maybe a
runParser :: Parser a -> C.ByteString -> Maybe (a, C.ByteString)
runParser = runStateT
{-# INLINE runParser #-}
int :: Parser Int
int = coerce $ C.readInt . C.dropWhile isSpace
{-# INLINE int #-}
int1 :: Parser Int
int1 = fmap (subtract 1) int
{-# INLINE int1 #-}
char :: Parser Char
char = coerce C.uncons
{-# INLINE char #-}
byte :: Parser Word8
byte = coerce B.uncons
{-# INLINE byte #-}
skipSpaces :: Parser ()
skipSpaces = modify' (C.dropWhile isSpace)
{-# INLINE skipSpaces #-}
lowerBoundM :: (Monad m) => Int -> Int -> (Int -> m Bool) -> m Int
lowerBoundM low high p = go low high where { go !low !high | high <= low = return high | otherwise = p mid >>= bool (go (mid + 1) high) (go low mid) where { mid = low + unsafeShiftRL (high - low) 1}}
{-# INLINE lowerBoundM #-}
upperBoundM :: (Monad m) => Int -> Int -> (Int -> m Bool) -> m Int
upperBoundM low high p = do { flg <- p high; if flg then return high else subtract 1 <$!> lowerBoundM low high (fmap not . p)}
{-# INLINE upperBoundM #-}
lowerBound :: Int -> Int -> (Int -> Bool) -> Int
lowerBound low high p = runIdentity (lowerBoundM low high (return . p))
{-# INLINE lowerBound #-}
upperBound :: Int -> Int -> (Int -> Bool) -> Int
upperBound low high p = runIdentity (upperBoundM low high (return . p))
{-# INLINE upperBound #-}
-------------------------------------------------------------------------------
-- Data.ByteString.LCP
-------------------------------------------------------------------------------
newtype LCPArray = LCPArray{getLCPArray :: U.Vector Int} deriving (Show)
naiveLCP :: B.ByteString -> B.ByteString -> Int
naiveLCP xs ys = go 0 where { !n = min (B.length xs) (B.length ys); go !i | i < n && B.unsafeIndex xs i == B.unsafeIndex ys i = go (i + 1) | otherwise = i}
buildLCPArray :: B.ByteString -> SuffixArray -> LCPArray
buildLCPArray bs sa = LCPArray $ U.create $ do { let { !n = B.length bs; rank = U.unsafeAccumulate (flip const) (U.generate (n + 1) id) . U.imap (flip (,)) $ getSuffixArray sa}; lcp <- UM.replicate (n + 1) (0 :: Int); let { go !i !h | i < n = do { let { xs = B.unsafeDrop (i + h) bs}; let { ys = B.unsafeDrop (getSuffixStartPos sa (U.unsafeIndex rank i - 1) + h) bs}; let { h' = h + naiveLCP xs ys}; UM.unsafeWrite lcp (U.unsafeIndex rank i - 1) h'; go (i + 1) . max 0 $ h' - 1} | otherwise = return lcp}; go 0 0}

Score : 100 points

Problem Statement

You are given a string of length N. Calculate the number of distinct substrings of S.

Constraints

1 \leq N \leq 500,000

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer.

Sample Input 1

abcbcba

Sample Output 1

21

Sample Input 2

mississippi

Sample Output 2

53

Sample Input 3

ababacaca

Sample Output 3

33

Sample Input 4

aaaaa

Sample Output 4

5


module Main where

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

main :: IO ()
main = do
    [n, x, t] <- map read . words <$> getLine
    print $ ((n - 1 + x) `div` x) * t

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


import Data.List
main = do
  [n,x,t] <- map (read::String->Int) . words <$> getLine
  print $ if (mod n x)==0 then (div n x)*t else (1+div n x)*t


import Data.Char

main = getLine >>= putStrLn . compute

compute :: String -> String
compute s
  | flag = "Yes"
  | True = "No"
  where
    flag = mod (sum $ map digitToInt s) 9 == 0

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


{-# OPTIONS_GHC -Wno-tabs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE BangPatterns #-}

-- Default Imports

import Control.Monad
import Control.Monad.ST
import Control.Monad.Trans.Class

import qualified Control.Monad.Reader as Reader
import Control.Monad.Reader (Reader, ReaderT, runReader, runReaderT)

import qualified Data.Array.MArray as MArray
import qualified Data.Array.ST as STArray
import Data.Array.ST (STArray, STUArray, runSTArray, runSTUArray)
import Data.Ix (Ix)

import qualified Data.Bits as Bits
import Data.Bits ((.&.), (.|.))

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)

import qualified Data.Char as Char
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import Data.Set (Set)

import qualified Data.Vector as Vector
import qualified Data.Vector.Generic as GVector
import qualified Data.Vector.Mutable as MVector
import Data.Vector.Mutable (STVector)
import qualified Data.Vector.Unboxed as UVector

import Numeric

import Debug.Trace
-- ----------

-- Custom Import Here

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

-- Default Definitions

type Vector = Vector.Vector
-- type GVector = GVector.Vector
type UVector = UVector.Vector

readIntToList :: IO [Int]
readIntToList = List.unfoldr (fmap (second $ BS.dropWhile Char.isSpace) . BS.readInt) <$> BS.getLine

readToList :: Read a => IO [a]
readToList = List.unfoldr (fmap (mapTaken . mapRemain) . span' (not . Char.isSpace)) <$> BS.getLine
	where
		mapTaken  = first $ read . BS.unpack
		mapRemain = second $ BS.dropWhile Char.isSpace
		span' pred s
			| BS.null taken = Nothing
			| otherwise     = Just (taken, remain')
			where
				(taken, remain) = BS.span pred s
				remain' = BS.dropWhile Char.isSpace remain

readToListN :: Read a => Int -> IO [a]
readToListN n = take n <$> readToList

readIntToVector :: IO (Vector Int)
readIntToVector = Vector.unfoldr (fmap stripRemain . BS.readInt) <$> BS.getLine
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToUVector :: IO (UVector.Vector Int)
readIntToUVector = UVector.unfoldr (fmap stripRemain . BS.readInt) <$> BS.getLine
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToVectorN :: Int -> IO (Vector.Vector Int)
readIntToVectorN n = Vector.unfoldrN n (fmap stripRemain . BS.readInt) <$> BS.getLine
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToUVectorN :: Int -> IO (UVector.Vector Int)
readIntToUVectorN n = UVector.unfoldrN n (fmap stripRemain . BS.readInt) <$> BS.getLine
	where stripRemain = second $ BS.dropWhile Char.isSpace

first :: (a -> a') -> (a, b) -> (a', b)
first f (a, b) = (f a, b)

second :: (b -> b') -> (a, b) -> (a, b')
second f (a, b) = (a, f b)

average :: Fractional a => [a] -> a
average xs = sum xs / (fromIntegral . length) xs

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

main :: IO ()
main = do
	n <- readLn :: IO Int
	xs <- readIntToList
	let xs' = tail $ List.scanl' max 0 xs
	print $ sum $ zipWith (-) xs' xs

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


import Control.Monad
import Data.List

solve 0 xs = [[]]
solve _ [] = []
solve n (x:xs) = [x:y | y <- solve (n-1) xs] ++ solve n xs

isT a b c = (a + b > c && a + c > b && b + c > a)

main = do
    n <- readLn :: IO Int
    ls <- map read . words <$> getLine :: IO [Int]
    if n >= 3
        then print $ length $ filter (\xs -> (length $ group $ sort xs) == 3 && isT (xs!!0) (xs!!1) (xs!!2)) $ map sort $ solve 3 ls
        else print $ 0

Score : 200 points

Problem Statement

We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.

In how many ways can we choose three of the sticks with different lengths that can form a triangle?

That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:

L_i, L_j, and L_k are all different.

There exists a triangle whose sides have lengths L_i, L_j, and L_k.

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 \cdots L_N

Output

Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

Sample Input 1

5
4 4 9 7 5

Sample Output 1

5

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

Sample Input 2

6
4 5 4 3 3 5

Sample Output 2

8

We have two sticks for each of the lengths 3, 4, and 5. To satisfy the first condition, we have to choose one from each length.

There is a triangle whose sides have lengths 3, 4, and 5, so we have 2 ^ 3 = 8 triples (i, j, k) that satisfy the conditions.

Sample Input 3

10
9 4 6 1 9 6 10 6 6 8

Sample Output 3

39

Sample Input 4

2
1 1

Sample Output 4

0

No triple (i, j, k) satisfies 1 \leq i < j < k \leq N, so we should print 0.


{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE MultiWayIf          #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ScopedTypeVariables #-}
import           Control.Monad
import           Control.Monad.ST
import           Control.Monad.State
import           Control.Monad.Trans.State
import           Data.Array.IArray
import           Data.Array.ST
import           Data.Array.Unboxed
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Int                    (Int64)
import           Data.List
import           Data.Maybe
import           Data.Proxy
import           Data.Sequence               (Seq, (<|), (><), (|>))
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.STRef
import qualified Data.Vector                 as V
import qualified Data.Vector.Mutable         as VM
import qualified Data.Vector.Unboxed         as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import           Numeric

main :: IO ()
main = do
  n <- readLn :: IO Int
  when (n == 0 || n == 1) $ print 0
  ls <- readLnAsListWith unconsInt

  print $ (`div`6) $ length [(i,j,k) |
           i <- ls,
           j <- ls,
           i /= j,
           k <- ls,
           j /= k,
           k /= i,
           i + j > k, j + k > i, k + i > j]

-- converter
unconsChar :: StateT BS.ByteString Maybe Char
unconsChar = StateT BS.uncons

unconsInt :: StateT BS.ByteString Maybe Int
unconsInt = StateT $ BS.readInt . BS.dropWhile isSpace

unconsInteger :: StateT BS.ByteString Maybe Integer
unconsInteger = StateT $ BS.readInteger . BS.dropWhile isSpace

-- 1D Data
-- for list
readLnAsListWith :: StateT BS.ByteString Maybe a -> IO [a]
readLnAsListWith !st = unfoldr (runStateT st) <$> BS.getLine

-- for array (boxed or unboxed)
readLnAsArrayWith :: IArray a e => StateT BS.ByteString Maybe e -> Int -> IO (a Int e)
readLnAsArrayWith !st !n = listArray (1,n) <$> readLnAsListWith st

-- for boxed vector
readLnAsVecWith :: StateT BS.ByteString Maybe a -> Int -> IO (V.Vector a)
readLnAsVecWith !st !n = V.unfoldrN n (runStateT st) <$> BS.getLine

-- for unboxed vector
readLnAsUVecWith :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> IO (VU.Vector a)
readLnAsUVecWith !st !n = VU.unfoldrN n (runStateT st) <$> BS.getLine

-- example: 1D tuple vector
readLnAsUVecWith2Tuple :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> IO (VU.Vector (a,a))
readLnAsUVecWith2Tuple !st !n = VU.replicateM n $ (\vec -> (vec VU.! 0, vec VU.! 1)) <$> readLnAsUVecWith st 2

-- 2D Data
-- n: number of lines
-- m: number of values per a line

-- for boxed array
readLnAs2DArrayWith :: IArray a e => StateT BS.ByteString Maybe e -> Int -> Int -> IO (a (Int,Int) e)
readLnAs2DArrayWith !st !n !m = listArray ((1,1),(n,m)) . unfoldr (runStateT st) . BS.concat <$> replicateM n BS.getLine

-- for boxed vector
readLnAs2DVecWith :: StateT BS.ByteString Maybe a -> Int -> Int -> IO (V.Vector (V.Vector a))
readLnAs2DVecWith !st !n !m = V.replicateM n $ V.unfoldrN m (runStateT st) <$> BS.getLine

-- for unboxed vector
readLnAs2DUVecWith :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> Int -> IO (V.Vector (VU.Vector a))
readLnAs2DUVecWith !st !n !m = V.replicateM n $ VU.unfoldrN m (runStateT st) <$> BS.getLine


solve :: [Int] -> Int
solve [x,k,d]
 | even exceededNumberOfWalking = abs (absX - numberOfWalking * d)
 | otherwise                    = abs (absX - (numberOfWalking + 1) * d)
  where absX = abs x
        numberOfWalking = min k (x `div` d)
        exceededNumberOfWalking = k - numberOfWalking
main = print =<< solve . map read . words <$> getLine

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


import Data.List
import Data.Char
import Data.Maybe
import Control.Monad
import qualified Data.ByteString.Char8 as BS8
import qualified Data.Vector as Vector
import Data.Vector ((!))

main :: IO ()
main = do
  [x, k, d] <- unfoldr (BS8.readInteger . BS8.dropWhile isSpace) <$> BS8.getLine

  let
    (n, m) = x `divMod` d
    o = minimum $ map abs [m - d, m + d]
    ans = abs $ if k >= n then
        if (k - n) `mod` 2 == 0 then m else o
      else minimum $ map abs [x + k * d, x - k * d]

  print ans


main = do
    a <- readLn :: IO Int
    if (a >= 30) then putStrLn "Yes"
    else putStrLn "No"

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


import Control.Applicative
import Data.Bool (bool)

main :: IO ()
main = solve <$> readLn >>= putStrLn

solve :: Int -> String
solve x = bool "No" "Yes" $ x >= 30


import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T

main :: IO ()
main = do
  x <- unsafeTextToInt <$> T.getLine :: IO Int
  putStrLn $ if 30 <= x then "Yes" else "No"

unsafeTextToInt :: T.Text -> Int
unsafeTextToInt s = case T.signed T.decimal s of
  Right (n, _) -> n
{-# INLINE unsafeTextToInt #-}


{-# LANGUAGE BangPatterns     #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiWayIf       #-}
import           Control.Monad
import           Control.Monad.ST
import           Control.Monad.State
import           Control.Monad.Trans.State
import           Data.Array.IArray
import           Data.Array.ST
import           Data.Array.Unboxed
import           Data.Bits
import qualified Data.ByteString.Char8     as BS
import           Data.Char
import           Data.Graph
import           Data.Int                  (Int64)
import           Data.List
import           Data.Maybe
import           Data.Proxy
import           Data.Sequence             (Seq, (<|), (><), (|>))
import qualified Data.Sequence             as Seq
import qualified Data.Set                  as S
import           Data.STRef
import qualified Data.Vector               as V
import qualified Data.Vector.Unboxed       as VU
import           Numeric

main :: IO ()
main = do
  n <- readLn :: IO Int
  cvec <- readLnAsUVecWith unconsChar n
  print $ solve n cvec

solve :: Int -> VU.Vector Char -> Int
solve n vec = go 0 (n-1) 0
  where go i j a = let l = vec VU.! i
                       r = vec VU.! j
                   in if | i >= j -> a
                         | otherwise -> if | l == 'W' && r == 'R' -> go (i+1) (j-1) (a+1)
                                           | l /= 'W' && r == 'R' -> go (i+1) j a
                                           | l == 'W' && r /= 'R' -> go i (j-1) a
                                           | l /= 'W' && r /= 'R' -> go (i+1) (j-1) a

-- converter
unconsChar :: StateT BS.ByteString Maybe Char
unconsChar = StateT BS.uncons

unconsInt :: StateT BS.ByteString Maybe Int
unconsInt = StateT $ BS.readInt . BS.dropWhile isSpace

unconsInteger :: StateT BS.ByteString Maybe Integer
unconsInteger = StateT $ BS.readInteger . BS.dropWhile isSpace

-- 1D Data
-- for list
readLnAsListWith :: StateT BS.ByteString Maybe a -> IO [a]
readLnAsListWith !st = unfoldr (runStateT st) <$> BS.getLine

-- for boxed array
readLnAsArrayWith :: StateT BS.ByteString Maybe a -> Int -> IO (Array Int a)
readLnAsArrayWith !st !n = listArray (1,n) <$> readLnAsListWith st

-- for unboxed array
readLnAsUArrayInt :: Int -> IO (UArray Int Int)
readLnAsUArrayInt !n = listArray (1,n) <$> readLnAsListWith unconsInt

readLnAsUArrayChar :: Int -> IO (UArray Int Char)
readLnAsUArrayChar !n = listArray (1,n) <$> readLnAsListWith unconsChar

-- for boxed vector
readLnAsVecWith :: StateT BS.ByteString Maybe a -> Int -> IO (V.Vector a)
readLnAsVecWith !st !n = V.unfoldrN n (runStateT st) <$> BS.getLine

-- for unboxed vector
readLnAsUVecWith :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> IO (VU.Vector a)
readLnAsUVecWith !st !n = VU.unfoldrN n (runStateT st) <$> BS.getLine

-- example: 1D tuple vector
readLnAsUVecWith2Tuple :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> IO (VU.Vector (a,a))
readLnAsUVecWith2Tuple !st !n = VU.replicateM n $ (\vec -> (vec VU.! 0, vec VU.! 1)) <$> readLnAsUVecWith st 2

-- 2D Data
-- n: number of lines
-- m: number of values per a line

-- for boxed array
readLnAs2DArrayWith :: StateT BS.ByteString Maybe a -> Int -> Int -> IO (Array (Int,Int) a)
readLnAs2DArrayWith !st !n !m = listArray ((1,1),(n,m)) . unfoldr (runStateT st) . BS.concat <$> replicateM n BS.getLine

-- for boxed vector
readLnAs2DVecWith :: StateT BS.ByteString Maybe a -> Int -> Int -> IO (V.Vector (V.Vector a))
readLnAs2DVecWith !st !n !m = V.replicateM n $ V.unfoldrN m (runStateT st) <$> BS.getLine

-- for unboxed vector
readLnAs2DUVecWith :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> Int -> IO (V.Vector (VU.Vector a))
readLnAs2DUVecWith !st !n !m = V.replicateM n $ VU.unfoldrN m (runStateT st) <$> BS.getLine

Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3


Score: 100 points

Problem Statement

M-kun is a competitor in AtCoder, whose highest rating is X.

In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:

From 400 through 599: 8-kyu

From 600 through 799: 7-kyu

From 800 through 999: 6-kyu

From 1000 through 1199: 5-kyu

From 1200 through 1399: 4-kyu

From 1400 through 1599: 3-kyu

From 1600 through 1799: 2-kyu

From 1800 through 1999: 1-kyu

What kyu does M-kun have?

Constraints

400 \leq X \leq 1999

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the kyu M-kun has, as an integer.
For example, if he has 8-kyu, print 8.

Sample Input 1

725

Sample Output 1

7

M-kun's highest rating is 725, which corresponds to 7-kyu.

Thus, 7 is the correct output.

Sample Input 2

1600

Sample Output 2

2

M-kun's highest rating is 1600, which corresponds to 2-kyu.

Thus, 2 is the correct output.


main = do
  x <- readLn :: IO Int
  putStrLn $ show $ 8 - div (x-400) 200