{-# LANGUAGE BangPatterns #-}
import Control.Arrow (second)
import Control.Monad
import Control.Monad.Fix
import Data.List (foldl')
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as VM
import qualified Data.ByteString.Char8 as B
import System.IO.Unsafe

modular :: Int
modular = 1000000007

solve :: Int -> B.ByteString -> B.ByteString -> Int
solve !n !s1 !s2 = (\(_,_,acc) -> acc) $ foldl' (\(!pre1,!pre2,!acc) i ->
  let ch1 = s1 `B.index` i; ch2 = s2 `B.index` i in
  if ch1 == pre1  -- skip if letters are same as previous
    then (pre1,pre2,acc)
    else
      if pre1 == pre2 then (ch1,ch2,2 `times` acc)
      else if ch1 == ch2 then (ch1,ch2,acc)
      else (ch1,ch2,3 `times` acc)
  ) (let ch1 = B.head s1; ch2 = B.head s2 in (ch1,ch2,if ch1 == ch2 then 3 else 6)) [1..n-1]
  where
    times !x !y = (x * y) `mod` modular

main = do
  let readInt = fmap (second B.tail) . B.readInt

  Just (n,_) <- readInt <$> B.getLine
  s1 <- B.getLine
  s2 <- B.getLine
  print $ solve n s1 s2


import Control.Applicative
import Data.Monoid
import Data.List

data Subsequence = Subsequence
    { str :: String
    , indicies :: [Int] } deriving Show

emptySubseq :: Subsequence
emptySubseq = Subsequence "" []

allStrings :: [String] -> [String]
allStrings alphabet =  alphabet <> ((++) <$> allStrings alphabet <*> alphabet)

dict = allStrings $ map (: []) ['a'..'z']

{-
insertAndReturnSeqIdx :: Int -> [Int] -> Int -> ([Int], Int)
insertAndReturnSeqIdx i [] a = ([i], a)
insertAndReturnSeqIdx i ix a
    | i < head ix = (i : ix, a)
    | not $ null ix = let
        (res, newA) = insertAndReturnSeqIdx i (tail ix) (a + 1) in
        (head ix : res, newA)
    | null ix = ([i], a)

-- recurrence relation between subsequences
-- TODO: Tabulation
reccur :: V.Vector Char -> Subsequence -> Int -> Subsequence
reccur input prevSeq idx = Subsequence newStr newIndicies
      where (newIndicies, seqIdx) =
                insertAndReturnSeqIdx idx (indicies prevSeq) 0
            (front, end) = splitAt seqIdx $ str prevSeq
            newStr = front ++ ((input V.! idx) : end)

isSubseq Subsequence sx =
-}

{-
search :: V.Vector Char -> String -> Either String Int
search input target = do
    let limit = length target
    let inputLen = V.length input
    map
-}

search :: String -> [String] -> String
search input dict
    | isSubsequenceOf (head dict) input = search input (tail dict)
    | otherwise = head dict

{-
solve :: V.Vector Char -> Int
solve input =
-}

main = do
    --input <- V.fromList <$> getLine
    input <- getLine
    let res = search input dict
    print res

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

Score : 600 points

Problem Statement

A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters.
For example, arc, artistic and (an empty string) are all subsequences of artistic; abc and ci are not.

You are given a string A consisting of lowercase English letters.
Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A.
If there are more than one such string, find the lexicographically smallest one among them.

Constraints

1 \leq |A| \leq 2 \times 10^5

A consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

A

Output

Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.

Sample Input 1

atcoderregularcontest

Sample Output 1

b

The string atcoderregularcontest contains a as a subsequence, but not b.

Sample Input 2

abcdefghijklmnopqrstuvwxyz

Sample Output 2

aa

Sample Input 3

frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn

Sample Output 3

aca

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.


Score : 100 points

Problem Statement

You are given a three-digit positive integer N.

Determine whether N is a palindromic number.

Here, a palindromic number is an integer that reads the same backward as forward in decimal notation.

Constraints

100≤N≤999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a palindromic number, print Yes; otherwise, print No.

Sample Input 1

575

Sample Output 1

Yes

N=575 is also 575 when read backward, so it is a palindromic number. You should print Yes.

Sample Input 2

123

Sample Output 2

No

N=123 becomes 321 when read backward, so it is not a palindromic number. You should print No.

Sample Input 3

812

Sample Output 3

No


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

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import Text.Printf

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

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

main = do
	s <- getLine
	putStrLn $ which "Yes" "No" $ s == reverse s


import Control.Monad

-- 最小公倍数
lcm' a b = head [ x | let c = max a b, x <- [c,c+1..], mod x a == 0 && mod x b ==0]

main = do
  line <- readLn
  args <- replicateM line readLn
  print $ solve args

solve :: [Int] -> Int
solve args = foldl lcm' 1 args

Score : 300 points

Problem Statement

We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly T_i seconds.

Initially, the hand of every clock stands still, pointing directly upward.

Now, Dolphin starts all the clocks simultaneously.

In how many seconds will the hand of every clock point directly upward again?

Constraints

1≤N≤100

1≤T_i≤10^{18}

All input values are integers.

The correct answer is at most 10^{18} seconds.

Input

Input is given from Standard Input in the following format:

N
T_1
:
T_N

Output

Print the number of seconds after which the hand of every clock point directly upward again.

Sample Input 1

2
2
3

Sample Output 1

6

We have two clocks. The time when the hand of each clock points upward is as follows:

Clock 1: 2, 4, 6, ... seconds after the beginning

Clock 2: 3, 6, 9, ... seconds after the beginning

Therefore, it takes 6 seconds until the hands of both clocks point directly upward.

Sample Input 2

5
2
5
10
1000000000000000000
1000000000000000000

Sample Output 2

1000000000000000000


import Data.List
import Control.Monad
main = readLn >>= flip replicateM readLn >>= print . solve

solve :: [Int] -> Int
solve = foldl' lcm 1


--{-# LANGUAGE BangPatterns #-}
--{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE ViewPatterns #-}
--{-# LANGUAGE OverloadedStrings #-}
--{-# LANGUAGE Strict #-}
--{-# LANGUAGE NumericUnderscores #-}
--{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE MultiWayIf #-}

import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map.Strict as MPS
import qualified Data.Map as MP
import qualified Data.Set as ST
import qualified Data.Sequence as SQ
import Data.Array
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.IO
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Char
import Data.Bits
import Data.List
import Data.Tuple
import Data.Functor
import Data.IORef
import Data.STRef
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Control.Monad.State.Strict
import Debug.Trace
-- import qualified Data.Vector.Algorithms.Merge as VAM
-- import qualified Data.Heap as HP
-- import Numeric.Extra
-- import Data.Tuple.Extra
-- import Data.List.Extra

--------------------------------------------------------------------------
type Graph = V.Vector [(Int,Int)]
type Distance = VUM.IOVector Int
type Queue = ST.Set (Int, Int)
data Direction = Directed | Undirected

buildGraph :: Direction -> Int -> V.Vector (Int, (Int, Int)) -> Graph
buildGraph direction vertex pathInfo =
  case direction of
    Directed -> V.accumulate step (V.replicate vertex []) pathInfo
    Undirected -> V.accumulate step (V.replicate vertex []) pathInfo'
  where
    step xs v = v:xs
    pathInfo' = pathInfo V.++ (V.map (\(a,(b,c)) -> (b,(a,c))) pathInfo)

dijkstra :: Int -> Int -> Graph -> IO Distance
dijkstra vertex from graph = do
  distance <- VUM.replicate vertex (10^9) :: IO Distance
  VUM.write distance from 0
  trav graph distance (ST.singleton (0, from))
  where
    trav :: Graph -> Distance -> Queue -> IO Distance
    trav graph distance queue
      | ST.null queue = return distance
      | otherwise = do
          tmp <- VUM.read distance from
          case compare acc tmp of
            LT -> update from acc distance queue' >>= trav graph distance
            EQ -> update from acc distance queue' >>= trav graph distance
            GT -> trav graph distance queue'
      where
        ((acc, from), queue') = ST.deleteFindMin queue

    update :: Int -> Int -> Distance -> Queue -> IO Queue
    update f a dist q = update' a dist (graph V.! f) q

    update' :: Int -> Distance -> [(Int, Int)] -> Queue -> IO Queue
    update' _ _ [] q = return q
    update' a dist ((to, cost):xs) q = do
      tmp <- VUM.read dist to
      case compare a' tmp of
        LT -> VUM.write dist to a' >> update' a dist xs q'
        _ -> update' a dist xs q
      where
        a' = a + cost
        q' = ST.insert (a', to) q

connected :: Graph -> (Int, Int) -> Bool
connected graph (x,y) = not $ null $ filter ((==y) . fst) as
    where
        as = graph V.! x

main = do
  n <- int
  abcs <- V.replicateM (n-1) $ do
    [a,b,c] <- sLineToIntL
    return (m1 a,(m1 b,c))
  [q,k] <- sLineToIntL
  xys <- VU.map (\(x,y) -> (m1 x, m1 y)) <$> mLinesToTupleV q
  let graph = buildGraph Undirected n abcs

  dist <- dijkstra n (k-1) graph
  VU.forM_ xys $ \(x,y) -> do
    dx <- VUM.read dist x
    dy <- VUM.read dist y
    if connected graph (x,y)
        then print $ 2 * dx + dy
        else print $ dx + dy
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = bsToInt <$> BC.getLine

double :: IO Double
double = bsToDouble <$> BC.getLine

str :: IO String
str = BC.unpack <$> BC.getLine

strBS :: IO BC.ByteString
strBS = BC.getLine

-- convert
bsToInt :: BC.ByteString -> Int
bsToInt = fst . fromJust . BC.readInt

bsToDouble :: BC.ByteString -> Double
bsToDouble = read . BC.unpack

bsToIntTuple :: BC.ByteString -> (Int, Int)
bsToIntTuple bs = (a,b)
    where
        Just (a,bs') = parseInt bs
        Just (b,_) = parseInt bs'

bsToIntTriple :: BC.ByteString -> (Int, Int, Int)
bsToIntTriple bs = (a,b,c)
    where
        Just (a,bs') = parseInt bs
        Just (b,bs'') = parseInt bs'
        Just (c,_) = parseInt bs''

parseInt :: BC.ByteString -> Maybe (Int, BC.ByteString)
parseInt = BC.readInt . BC.dropWhile isSpace

-- single line
fromSLineL :: (BC.ByteString -> a) -> IO [a]
fromSLineL f =  map f . BC.words <$> strBS

-- from single line to List / VU.Vector
sLineToIntL :: IO [Int]
sLineToIntL = fromSLineL bsToInt

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

sLineToStrL :: IO [String]
sLineToStrL = fromSLineL BC.unpack

sLineToStrBSL :: IO [BC.ByteString]
sLineToStrBSL = fromSLineL id

sLineToIntV :: Int -> IO (VU.Vector Int)
sLineToIntV n = VU.unfoldrN n parseInt <$> BC.getLine

sLineToDoubleV :: IO (VU.Vector Double)
sLineToDoubleV = VU.fromList . map bsToDouble . BC.words <$> BC.getLine

-- multiple lines
fromMLinesL :: Int -> (BC.ByteString -> a) -> IO [a]
fromMLinesL n f = replicateM n (f <$> strBS)

fromMLinesV :: VU.Unbox a => Int -> (BC.ByteString -> a) -> IO (VU.Vector a)
fromMLinesV n f = VU.replicateM n (f <$> strBS)

-- from multiple lines to List / VU.Vector
mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = fromMLinesL n bsToInt

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = fromMLinesL n bsToDouble

mLinesToStrL :: Int -> IO [String]
mLinesToStrL n = fromMLinesL n BC.unpack

mLinesToStrBSL :: Int -> IO [BC.ByteString]
mLinesToStrBSL n = fromMLinesL n id

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = fromMLinesL n bsToIntTuple

mLinesToTripleL :: Int -> IO [(Int, Int, Int)]
mLinesToTripleL n = fromMLinesL n bsToIntTriple

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = fromMLinesV n bsToInt

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = fromMLinesV n bsToDouble

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = fromMLinesV n bsToIntTuple

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = fromMLinesV n bsToIntTriple

-- output
yesnoL :: Bool -> IO ()
yesnoL cond
    | cond = putStrLn "Yes"
    | otherwise = putStrLn "No"

yesnoU :: Bool -> IO ()
yesnoU cond
    | cond = putStrLn "YES"
    | otherwise = putStrLn "NO"

-- others
strToChr :: String -> Char
strToChr [x] = x

chrToStr :: Char -> String
chrToStr x = [x]

m1 :: Int -> Int
m1 = subtract 1

toDouble :: Int -> Double
toDouble = fromIntegral

toInt :: Double -> Int
toInt = floor

sqToList :: SQ.Seq a -> [a]
sqToList sq =
    case SQ.viewl sq of
        l SQ.:< sq' -> l : sqToList sq'
        SQ.EmptyL -> []

Score : 400 points

Problem Statement

You are given a tree with N vertices.

Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.

The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.

You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):

find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.

Constraints

3≤N≤10^5

1≤a_i,b_i≤N (1≤i≤N-1)

1≤c_i≤10^9 (1≤i≤N-1)

The given graph is a tree.

1≤Q≤10^5

1≤K≤N

1≤x_j,y_j≤N (1≤j≤Q)

x_j≠y_j (1≤j≤Q)

x_j≠K,y_j≠K (1≤j≤Q)

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}

Output

Print the responses to the queries in Q lines.

In the j-th line j(1≤j≤Q), print the response to the j-th query.

Sample Input 1

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

Sample Output 1

3
2
4

The shortest paths for the three queries are as follows:

Query 1: Vertex 2 → Vertex 1 → Vertex 2 → Vertex 4 : Length 1+1+1=3

Query 2: Vertex 2 → Vertex 1 → Vertex 3 : Length 1+1=2

Query 3: Vertex 4 → Vertex 2 → Vertex 1 → Vertex 3 → Vertex 5 : Length 1+1+1+1=4

Sample Input 2

7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7

Sample Output 2

5
14
22

The path for each query must pass Vertex K=2.

Sample Input 3

10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10

Sample Output 3

17000000000


import qualified Data.ByteString.Char8 as BC
import Data.Maybe (fromJust)
import Data.List
import Data.Array.IO
import Control.Monad

type Memo = IOArray (Int, Int) Int

main = do
  n <- readLn :: IO Int
  edge <- (\[x,y,z] -> zip3 x y z) . transpose <$> replicateM (n-1) getIntListBC
  [q, k] <- map read . words <$> getLine :: IO [Int]
  query <- (\[x,y] -> zip x y) . transpose <$> getInt2DListBC
  adjacency <- newArray ((1, 1), (n, n)) (maxBound :: Int) :: IO Memo
  mark <- newArray (1, n) False :: IO (IOArray Int Bool)
  weight <- newArray (1, n) 0 :: IO (IOArray Int Int)
  neighbors <- newArray ((1, 0), (n, n-1)) 0 :: IO Memo
  foldM (initEdge neighbors) adjacency edge
  foldM memoize adjacency [1..n]
  kn <- readArray neighbors (k, 0)
  writeArray mark k True
  kNeighbors <- readNeighbors neighbors k kn
  foldM (search adjacency weight neighbors k k) mark kNeighbors
  ans <- mapM (readWeight weight k) query
  putStrLn . unlines . map show $ ans

bsToInt :: BC.ByteString -> Int
bsToInt = fst . fromJust . BC.readInt

getIntListBC :: IO [Int]
getIntListBC = map bsToInt . BC.words <$> BC.getLine

getInt2DListBC :: IO [[Int]]
getInt2DListBC = map (map bsToInt . BC.words) . BC.lines <$> BC.getContents

memoize :: Memo -> Int -> IO Memo
memoize memo i = do
  writeArray memo (i, i) 0
  return memo

initEdge :: Memo -> Memo -> (Int, Int, Int) -> IO Memo
initEdge neighbors memo (x, y, d) = do
  xn <- readArray neighbors (x, 0)
  yn <- readArray neighbors (y, 0)
  writeArray memo (x, y) d
  writeArray memo (y, x) d
  writeArray neighbors (x, 0) $ xn + 1
  writeArray neighbors (y, 0) $ yn + 1
  writeArray neighbors (x, (xn+1)) y
  writeArray neighbors (y, (yn+1)) x
  return memo

--始点k 前pre 現在i
search :: Memo -> IOArray Int Int -> Memo -> Int -> Int -> IOArray Int Bool -> Int -> IO (IOArray Int Bool)
search edge weight neighbors k pre mark i = do
  isMark <- readArray mark i
  case isMark of
    True -> do
      return mark
    False -> do
      writeArray mark i True
      wI <- readArray edge (pre, i)
      wSum <- readArray weight pre
      writeArray weight i (wSum+wI)
      n <- readArray neighbors (i, 0)
      nI <- readNeighbors neighbors i n
      return =<< foldM (search edge weight neighbors k i) mark nI

readNeighbors :: Memo -> Int -> Int -> IO [Int]
readNeighbors neighbors i n = mapM (\x -> readArray neighbors (i, x)) [1..n]

readWeight :: IOArray Int Int -> Int -> (Int, Int) -> IO Int
readWeight weight k (x, y) = do
  kx <- readArray weight x
  ky <- readArray weight y
  return $ kx + ky


import Control.Applicative

-- | slove
-- >>> solve 3 4
-- 6
-- >>> solve 2 2
-- 1

main = do
    (n : m : _) <- (map read . words) <$> getLine -- input: 123 456 789
    print $ solve n m

solve n m = (n - 1) * (m - 1)

Score : 100 points

Problem Statement

In K-city, there are n streets running east-west, and m streets running north-south. Each street running east-west and each street running north-south cross each other. We will call the smallest area that is surrounded by four streets a block. How many blocks there are in K-city?

Constraints

2 ≤ n, m ≤ 100

Input

Input is given from Standard Input in the following format:

n m

Output

Print the number of blocks in K-city.

Sample Input 1

3 4

Sample Output 1

6

There are six blocks, as shown below:

Sample Input 2

2 2

Sample Output 2

1

There are one block, as shown below:


main::IO()
main=do
  str<-getLine
  putStr ((head str):(((show.length.init.tail)str)++[last str,'\n']))

Score : 200 points

Problem Statement

The word internationalization is sometimes abbreviated to i18n.
This comes from the fact that there are 18 letters between the first i and the last n.

You are given a string s of length at least 3 consisting of lowercase English letters.
Abbreviate s in the same way.

Constraints

3 ≤ |s| ≤ 100 (|s| denotes the length of s.)

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the abbreviation of s.

Sample Input 1

internationalization

Sample Output 1

i18n

Sample Input 2

smiles

Sample Output 2

s4s

Sample Input 3

xyz

Sample Output 3

x1z


--import Data.List
--import Control.Monad

main = do
  n <- getLine
  a <- (map read . words) <$> getLine
  putStrLn $ solve a

solve:: [Int] -> String
solve a
  |  ttn >= kk = "Yes"
  | otherwise = "No"
  where
    ffa = filter (\x -> x `mod` 4 == 0) a
    ttn = length $ filter (\x -> x `mod` 2 == 0) ffa
    k = length a - length ffa * 3
    kk = if odd k then k + 1 else k

Score : 400 points

Problem Statement

We have a sequence of length N, a = (a_1, a_2, ..., a_N).
Each a_i is a positive integer.

Snuke's objective is to permute the element in a so that the following condition is satisfied:

For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If Snuke can achieve his objective, print Yes; otherwise, print No.

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

It is impossible to permute a so that the condition is satisfied.

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


-- Question C

import Control.Applicative
import Control.Monad

main = do
  n <- readLn ::IO Int
  xs <- map read . words <$> getLine
  putStrLn $ show (check xs n)

check :: [Int] -> Int -> String
check xs n
  | (m4th + 1 == oddth ) && (m4th + oddth == n) = "Yes"
  | m4th >= oddth  = "Yes"
  | otherwise = "No"
  where m4th = length (filter (\p -> p `mod` 4 == 0) xs)
        oddth = length (filter odd xs)


Score : 100 points

Problem Statement

This contest, AtCoder Beginner Contest, is abbreviated as ABC.

When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.

What is the abbreviation for the N-th round of ABC? Write a program to output the answer.

Constraints

100 ≤ N ≤ 999

Input

Input is given from Standard Input in the following format:

N

Output

Print the abbreviation for the N-th round of ABC.

Sample Input 1

100

Sample Output 1

ABC100

The 100th round of ABC is ABC100.

Sample Input 2

425

Sample Output 2

ABC425

Sample Input 3

999

Sample Output 3

ABC999


main :: IO ()
main = do
  n <- readLn :: IO Int
  print $ fst $ maximum $ map (\x -> (x, f x 0)) $ filter even [1..n]

f :: Int -> Int -> Int
f n i
  |odd $ n `div` 2 = i+1
  |otherwise = f n (i+1)

Score : 200 points

Problem Statement

Takahashi loves numbers divisible by 2.

You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique.

Here, the number of times an integer can be divisible by 2, is how many times the integer can be divided by 2 without remainder.

For example,

6 can be divided by 2 once: 6 -> 3.

8 can be divided by 2 three times: 8 -> 4 -> 2 -> 1.

3 can be divided by 2 zero times.

Constraints

1 ≤ N ≤ 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

7

Sample Output 1

4

4 can be divided by 2 twice, which is the most number of times among 1, 2, ..., 7.

Sample Input 2

32

Sample Output 2

32

Sample Input 3

1

Sample Output 3

1

Sample Input 4

100

Sample Output 4

64


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

readInt = fst . fromJust . BS.readInt

readIntList = map readInt . BS.words

getIntList = readIntList <$> BS.getLine

getIntNList n = map readIntList <$> replicateM (fromIntegral n) BS.getLine

getNum :: [[Int]] -> Int -> [Int] -> [Int] -> ([Int], [Int])
getNum [] n as bs = (as, bs)
getNum (xy : xys) n as bs
  | head xy == 1 = getNum xys n ((last xy) : as) bs
  | last xy == 1 = getNum xys n ((head xy) : as) bs
  | head xy == n = getNum xys n as ((last xy) : bs)
  | last xy == n = getNum xys n as ((head xy) : bs)
  | otherwise = getNum xys n as bs

judge :: [Int] -> [Int] -> String
judge (x : xs) ys
  | x `elem` ys = "POSSIBLE"
  | otherwise = "IMPOSSIBLE"

main = do
  [n, m] <- getIntList
  abs <- getIntNList m
  let (xs, ys) = getNum abs n [] []
  putStrLn $ judge xs ys

Score : 300 points

Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands.
For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands.
Each service connects two islands. The i-th service connects Island a_i and Island b_i.

Cat Snuke is on Island 1 now, and wants to go to Island N.
However, it turned out that there is no boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

Help him.

Constraints

3 ≤ N ≤ 200 000

1 ≤ M ≤ 200 000

1 ≤ a_i < b_i ≤ N

(a_i, b_i) \neq (1, N)

If i \neq j, (a_i, b_i) \neq (a_j, b_j).

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

POSSIBLE

Sample Input 2

4 3
1 2
2 3
3 4

Sample Output 2

IMPOSSIBLE

You have to use three boat services to get to Island 4.

Sample Input 3

100000 1
1 99999

Sample Output 3

IMPOSSIBLE

Sample Input 4

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

Sample Output 4

POSSIBLE

You can get to Island 5 by using two boat services: Island 1 -> Island 4 -> Island 5.


import Control.Applicative
import Control.Monad
import Data.List
import Data.Char
strToInt s = (read :: String -> Int) s
strToInteger s = (read :: String -> Integer) s
strToDouble s = (read :: String -> Double) s

main :: IO ()
main = do
    -- スペース区切り整数の入力
    [n, m] <- map strToInt . words <$> getLine
    ab <- replicateM m $ do
        [a, b] <- map strToInt . words <$> getLine
        return (a, b)
    -- 出力
    putStrLn $ if solve 2 ab n 1 then "POSSIBLE" else "IMPOSSIBLE"

solve :: Int -> [(Int, Int)] -> Int -> Int -> Bool
solve 0 _ _ _ = False
solve _ [] g s = if s == g then True else False
solve c ab g s = if (s == g) then True else (if null ships then False else or $ map (solve (c-1) ab g . snd) ships)
    where
        ships = filter ((== s) . fst) ab


main = do
  [n, k] <- map read . words <$> getLine :: IO [Int]
  a <- map read . words <$> getLine :: IO [Int]
  let d = foldl gcd 0 a
  putStrLn $ if any (\x -> x >= k && (x - k) `mod` d == 0) a then "POSSIBLE" else "IMPOSSIBLE"

Score : 300 points

Problem Statement

There is a box containing N balls. The i-th ball has the integer A_i written on it.
Snuke can perform the following operation any number of times:

Take out two balls from the box. Then, return them to the box along with a new ball, on which the absolute difference of the integers written on the two balls is written.

Determine whether it is possible for Snuke to reach the state where the box contains a ball on which the integer K is written.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq K \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

If it is possible for Snuke to reach the state where the box contains a ball on which the integer K is written, print POSSIBLE; if it is not possible, print IMPOSSIBLE.

Sample Input 1

3 7
9 3 4

Sample Output 1

POSSIBLE

First, take out the two balls 9 and 4, and return them back along with a new ball, abs(9-4)=5.
Next, take out 3 and 5, and return them back along with abs(3-5)=2.
Finally, take out 9 and 2, and return them back along with abs(9-2)=7.
Now we have 7 in the box, and the answer is therefore POSSIBLE.

Sample Input 2

3 5
6 9 3

Sample Output 2

IMPOSSIBLE

No matter what we do, it is not possible to have 5 in the box. The answer is therefore IMPOSSIBLE.

Sample Input 3

4 11
11 3 7 15

Sample Output 3

POSSIBLE

The box already contains 11 before we do anything. The answer is therefore POSSIBLE.

Sample Input 4

5 12
10 2 8 6 4

Sample Output 4

IMPOSSIBLE


import Data.List

main = do
    [_, k] <- map read . words <$> getLine
    l <- map read . words <$> getLine
    print $ sum . take k . reverse $ sort l

Score : 200 points

Problem Statement

Snuke has N sticks.
The length of the i-th stick is l_i.

Snuke is making a snake toy by joining K of the sticks together.

The length of the toy is represented by the sum of the individual sticks that compose it.
Find the maximum possible length of the toy.

Constraints

1 \leq K \leq N \leq 50

1 \leq l_i \leq 50

l_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
l_1 l_2 l_3 ... l_{N}

Output

Print the answer.

Sample Input 1

5 3
1 2 3 4 5

Sample Output 1

12

You can make a toy of length 12 by joining the sticks of lengths 3, 4 and 5, which is the maximum possible length.

Sample Input 2

15 14
50 26 27 21 41 7 42 35 7 5 5 36 39 1 45

Sample Output 2

386


main = print . abs . solve1 . map read . drop 1 . words =<< getContents

solve1 :: [Integer] -> Integer
solve1 xs =
    let diffs = zipWith (-) (drop 1 xs) xs
    in  solve2 diffs

maxVal = 1000000000

solve2 :: [Integer] -> Integer
solve2 [] = maxVal
solve2 (x:[]) = maxVal
solve2 xs =
    let l = take (length xs `div` 2) xs
        r = drop (length xs `div` 2) xs
        ls = solve2 l
        rs = solve2 r
        ms = (minHeads $ reverse l) + (minHeads r)
    in  if abs ms < abs ls && abs ms < abs rs then ms
        else if abs ls < abs rs then ls else rs

minHeads :: [Integer] -> Integer
minHeads xs = let (_, res) = foldr (\x (t, s) -> (t+x, min (abs (t+x)) (abs s))) (0, head xs) (tail xs) in res

Score : 300 points

Problem Statement

Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.

They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.

Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively.
They would like to minimize |x-y|.
Find the minimum possible value of |x-y|.

Constraints

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

-10^{9} \leq a_i \leq 10^{9}

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Print the answer.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value.

Sample Input 2

2
10 -10

Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10, y=-10, and thus |x-y|=20.


main :: IO ()
main = do
  _ <- getLine
  a <- reads2List :: IO [Int]
  print $ solve a

solve :: [Int] -> Int
solve a = minimum $ fmap (\n -> abs (2 * n - la')) (init a') where
  a' = scanl1 (+) a
  la' = last a'

s2List :: Read a => String -> [a]
s2List = fmap read . words

reads2List :: Read a => IO [a]
reads2List = do
  s <- getLine
  return (s2List s)


import Data.List
import Control.Applicative

listsumcut :: [Int]->[Int]->[Int]
listsumcut [x] accum =accum
listsumcut (x:xs) (a:accum) = listsumcut xs $ (a+2*x):a:accum

solver (x:y:[]) = abs (x-y)
solver (x:xs) = minimum $ map abs $ listsumcut xs [x-(sum xs)]

main :: IO ()
main = do
    -- スペース区切り整数の入力
    getLine
    list <- map read . words <$> getLine
    -- 出力
    putStrLn $ show $ solver list


import           Control.Monad
import           Data.Bits
import qualified Data.ByteString.Char8 as BS
import           Data.Maybe
import qualified Data.Vector.Unboxed   as V

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

main = do
  [n, p] <- getIntList
  as <- V.fromList <$> getIntList

  let calcNBiscuits b i res | i == n         = res
                            | (b .&. 1) == 1 = calcNBiscuits (b `shiftR` 1) (i + 1) (res + as V.! i)
                            | otherwise      = calcNBiscuits (b `shiftR` 1) (i + 1) res

      solve :: Int -> Int -> Int
      solve b res | b == (1 `shiftL` n) = res
                  | otherwise =
                    let numb = calcNBiscuits b 0 0
                    in solve (b+1) (res + (if numb `mod` 2 == p then 1 else 0))

  print $ solve 0 0

Score : 200 points

Problem Statement

There are N bags of biscuits. The i-th bag contains A_i biscuits.

Takaki will select some of these bags and eat all of the biscuits inside.
Here, it is also possible to select all or none of the bags.

He would like to select bags so that the total number of biscuits inside is congruent to P modulo 2.
How many such ways to select bags there are?

Constraints

1 \leq N \leq 50

P = 0 or 1

1 \leq A_i \leq 100

Input

Input is given from Standard Input in the following format:

N P
A_1 A_2 ... A_N

Output

Print the number of ways to select bags so that the total number of biscuits inside is congruent to P modulo 2.

Sample Input 1

2 0
1 3

Sample Output 1

2

There are two ways to select bags so that the total number of biscuits inside is congruent to 0 modulo 2:

Select neither bag. The total number of biscuits is 0.

Select both bags. The total number of biscuits is 4.

Sample Input 2

1 1
50

Sample Output 2

0

Sample Input 3

3 0
1 1 1

Sample Output 3

4

Two bags are distinguished even if they contain the same number of biscuits.

Sample Input 4

45 1
17 55 85 55 74 20 90 67 40 70 39 89 91 50 16 24 14 43 24 66 25 9 89 71 41 16 53 13 61 15 85 72 62 67 42 26 36 66 4 87 59 91 4 25 26

Sample Output 4

17592186044416


import Data.Bool

main = do
 [n,a,b,c,d] <- map read . words <$> getLine :: IO [Integer]
 putStrLn $ bool "NO" "YES" $ moderate n a b c d

moderate n a b c d
 | odd n = r >= abs (a-b)
 | otherwise = r - min c d <= abs (a-b) && r + max c d <= abs (a-b)
 where
  r = div (abs (a-b)) 2 * diff
  diff = d - c

Score : 400 points

Problem Statement

There are N squares in a row.
The leftmost square contains the integer A, and the rightmost contains the integer B. The other squares are empty.

Aohashi would like to fill the empty squares with integers so that the following condition is satisfied:

For any two adjacent squares, the (absolute) difference of the two integers in those squares is between C and D (inclusive).

As long as the condition is satisfied, it is allowed to use arbitrarily large or small integers to fill the squares.
Determine whether it is possible to fill the squares under the condition.

Constraints

3 \leq N \leq 500000

0 \leq A \leq 10^9

0 \leq B \leq 10^9

0 \leq C \leq D \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B C D

Output

Print YES if it is possible to fill the squares under the condition; print NO otherwise.

Sample Input 1

5 1 5 2 4

Sample Output 1

YES

For example, fill the squares with the following integers: 1, -1, 3, 7, 5, from left to right.

Sample Input 2

4 7 6 4 5

Sample Output 2

NO

Sample Input 3

48792 105960835 681218449 90629745 90632170

Sample Output 3

NO

Sample Input 4

491995 412925347 825318103 59999126 59999339

Sample Output 4

YES


import Data.Bool

main = do
 [n,a,b,c,d] <- map read . words <$> getLine :: IO [Integer]
 putStrLn $ bool "NO" "YES" $ moderate n a b c d

moderate n a b c d
 | odd n = r >= abs (a-b)
 | otherwise = r + min c d >= abs (a-b) && r + max c d <= abs (a-b)
 where
  r = div (abs (a-b)) 2 * diff
  diff = d - c


import qualified Data.ByteString.Char8 as BS

readString = map BS.unpack . BS.words

getString = readString <$> BS.getLine

calcDetail :: String -> Bool
calcDetail ss = a == b
  where
    (a, b) = splitAt (length ss `div` 2) ss

calc :: String -> Int
calc [s] = 0
calc (s1 : s2 : ss)
  | odd (length (s1 : s2 : ss)) = 1 + calc (s2 : ss)
  | calcDetail (s1 : s2 : ss) = 0
  | otherwise = 2 + calc ss

main = do
  [s] <- getString
  print $ length s - (calc (tail (reverse s)) + 1)

Score : 200 points

Problem Statement

We will call a string that can be obtained by concatenating two equal strings an even string.
For example, xyzxyz and aaaaaa are even, while ababab and xyzxy are not.

You are given an even string S consisting of lowercase English letters.
Find the length of the longest even string that can be obtained by deleting one or more characters from the end of S.
It is guaranteed that such a non-empty string exists for a given input.

Constraints

2 \leq |S| \leq 200

S is an even string consisting of lowercase English letters.

There exists a non-empty even string that can be obtained by deleting one or more characters from the end of S.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest even string that can be obtained.

Sample Input 1

abaababaab

Sample Output 1

6

abaababaab itself is even, but we need to delete at least one character.

abaababaa is not even.

abaababa is not even.

abaabab is not even.

abaaba is even. Thus, we should print its length, 6.

Sample Input 2

xxxx

Sample Output 2

2

xxx is not even.

xx is even.

Sample Input 3

abcabcabcabc

Sample Output 3

6

The longest even string that can be obtained is abcabc, whose length is 6.

Sample Input 4

akasakaakasakasakaakas

Sample Output 4

14

The longest even string that can be obtained is akasakaakasaka, whose length is 14.


judge :: String -> Bool
judge xs
  | s1 == s2  = True
  | otherwise = False
    where l = length xs `div` 2
          s1 = take l xs
          s2 = drop l xs

check :: String -> String
check [] = []
check xs
  | judge xs  = xs
  | otherwise = check (init $ init xs)

main = do
  str <- getLine
  let str' = if odd $ length str then init str else init $ init str
  putStrLn $ show $ length $ check str'


main :: IO ()
main = do
  s <- getLine
  print $ solve s

solve :: String -> Int
solve = length . go . reverse
  where
    go :: String -> String
    go [] = []
    go [x] = []
    go (x:y:z)
      | check z  = z
      | otherwise = go z
    check :: String -> Bool
    check str =
      let (ls, rs) = splitAt ((length str) `div` 2) str in
        ls == rs


-- Question C

import Control.Applicative
import Control.Monad

main = do
  n <- readLn ::IO Int
  zs <- (map read . words) <$> getLine
  putStr $ unwords ( map show ( try' n zs) )

try' n zs = if n `mod` 2 == 0
                then (reverse (try1 1 n [] zs)) ++ try2 2 n [] zs
                else (reverse (try2 2 n [] zs)) ++ try1 1 n [] zs

try1 :: Int -> Int -> [Int] -> [Int] -> [Int]
try1 i k ys xs
  | i > k = ys
  | otherwise = try1 (i+2) k ( ys ++ [xs !! (i-1)] ) xs

try2 :: Int -> Int -> [Int] -> [Int] -> [Int]
try2 i k ys xs
  | i > k = ys
  | otherwise = try2 (i+2) k ( ys ++ [xs !! (i-1)] ) xs

Score : 300 points

Problem Statement

You are given an integer sequence of length n, a_1, ..., a_n.
Let us consider performing the following n operations on an empty sequence b.

The i-th operation is as follows:

Append a_i to the end of b.

Reverse the order of the elements in b.

Find the sequence b obtained after these n operations.

Constraints

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

0 \leq a_i \leq 10^9

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print n integers in a line with spaces in between.
The i-th integer should be b_i.

Sample Input 1

4
1 2 3 4

Sample Output 1

4 2 1 3

After step 1 of the first operation, b becomes: 1.

After step 2 of the first operation, b becomes: 1.

After step 1 of the second operation, b becomes: 1, 2.

After step 2 of the second operation, b becomes: 2, 1.

After step 1 of the third operation, b becomes: 2, 1, 3.

After step 2 of the third operation, b becomes: 3, 1, 2.

After step 1 of the fourth operation, b becomes: 3, 1, 2, 4.

After step 2 of the fourth operation, b becomes: 4, 2, 1, 3.

Thus, the answer is 4 2 1 3.

Sample Input 2

3
1 2 3

Sample Output 2

3 1 2

As shown above in Sample Output 1, b becomes 3, 1, 2 after step 2 of the third operation. Thus, the answer is 3 1 2.

Sample Input 3

1
1000000000

Sample Output 3

1000000000

Sample Input 4

6
0 6 7 6 7 0

Sample Output 4

0 6 6 0 7 7


import qualified Data.ByteString.Char8 as BC
import qualified Data.IntMap as M
import Data.Maybe (fromJust)
import Data.List
import Data.Array.IO
import Control.Monad

type Memo = IOUArray Int Int

modN :: Int
modN = 10^9+7

main = do
  n <- readLn :: IO Int
  a <- getIntListBC
  check <- newArray (1, n) 0 :: IO Memo
  l <- numbering check a 1
  table <- newArray (0, n+1) 0 :: IO Memo
  makeTable table (n+1) (n+1)
  let k = [1..n+1]
      dup = n - l - 1
      cn = fact (n+1)
      cnl = fact (n-l-1)
  ans <- mapM (solve table cn cnl n l) k
  putStr $ unlines . map show $ ans

bsToInt :: BC.ByteString -> Int
bsToInt = fst . fromJust . BC.readInt

getIntListBC :: IO [Int]
getIntListBC = map bsToInt . BC.words <$> BC.getLine

numbering :: Memo -> [Int] -> Int -> IO Int
numbering memo [] n = return 0
numbering memo (i:is) n = do
  c <- readArray memo i
  case c of
    0 -> do
      writeArray memo i n
      return =<< numbering memo is $ n + 1
    _ -> do
      return $ n - c - 1

--x^n (mod modN)
(|^) :: Int -> Int -> Int
(|^) x n
  | n == 0    = 1
  | even n    = (mod (x * x) modN) |^ (n `div` 2)
  | otherwise = (flip mod modN) . (*x) $ x |^ (n - 1)

--x! (mod modN)
fact :: Int -> Int
fact n
  | n == 0    = 1
  | otherwise = (flip mod modN) . (*n) $ fact (n-1)

makeTable :: Memo -> Int -> Int -> IO Memo
makeTable table n (-1) = return table
makeTable table n i
  | n == i = do
    writeArray table i $ (fact n) |^ (10^9+5)
    makeTable table i $ i-1
  | otherwise = do
    ie <- readArray table (i+1)
    writeArray table i $ flip mod modN $ ie * (i+1)
    makeTable table i $ i-1

comb :: Memo -> Int -> Int -> Int -> IO Int
comb memo cn n k = do
  ik <- readArray memo k
  ink <- readArray memo $ n - k
  let tmp = flip mod modN $ cn * ik
      ans = flip mod modN $ tmp * ink
  return ans

solve :: Memo -> Int -> Int -> Int -> Int -> Int -> IO Int
solve table cn cnl n l k
  | k == 1 = return n
  | n - l >= k = do
    x <- comb table cn (n+1) k
    y <- comb table cnl (n-l-1) (k-1)
    return $ x - y
  | otherwise = comb table cn (n+1) k

Score : 600 points

Problem Statement

You are given an integer sequence of length n+1, a_1,a_2,...,a_{n+1}, which consists of the n integers 1,...,n.
It is known that each of the n integers 1,...,n appears at least once in this sequence.

For each integer k=1,...,n+1, find the number of the different subsequences (not necessarily contiguous) of the given sequence with length k, modulo 10^9+7.

Notes

If the contents of two subsequences are the same, they are not separately counted even if they originate from different positions in the original sequence.

A subsequence of a sequence a with length k is a sequence obtained by selecting k of the elements of a and arranging them without changing their relative order. For example, the sequences 1,3,5 and 1,2,3 are subsequences of 1,2,3,4,5, while 3,1,2 and 1,10,100 are not.

Constraints

1 \leq n \leq 10^5

1 \leq a_i \leq n

Each of the integers 1,...,n appears in the sequence.

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_{n+1}

Output

Print n+1 lines.
The k-th line should contain the number of the different subsequences of the given sequence with length k, modulo 10^9+7.

Sample Input 1

3
1 2 1 3

Sample Output 1

3
5
4
1

There are three subsequences with length 1: 1 and 2 and 3.

There are five subsequences with length 2: 1,1 and 1,2 and 1,3 and 2,1 and 2,3.

There are four subsequences with length 3: 1,1,3 and 1,2,1 and 1,2,3 and 2,1,3.

There is one subsequence with length 4: 1,2,1,3.

Sample Input 2

1
1 1

Sample Output 2

1
1

There is one subsequence with length 1: 1.

There is one subsequence with length 2: 1,1.

Sample Input 3

32
29 19 7 10 26 32 27 4 11 20 2 8 16 23 5 14 6 12 17 22 18 30 28 24 15 1 25 3 13 21 19 31 9

Sample Output 3

32
525
5453
40919
237336
1107568
4272048
13884156
38567100
92561040
193536720
354817320
573166440
818809200
37158313
166803103
166803103
37158313
818809200
573166440
354817320
193536720
92561040
38567100
13884156
4272048
1107568
237336
40920
5456
528
33
1

Be sure to print the numbers modulo 10^9+7.


import Data.List
import Debug.Trace
import qualified Data.IntMap as M

k = 1000000007
maxN = 100001

toMap = M.fromList . zip [0..]

fact i = facts M.! i
  where facts = toMap $ reverse $ foldl' (\z i -> head z * i `mod` k : z) [1] [1..maxN]

nCr n r = fact n * invfact r `mod` k * invfact (n-r) `mod` k
  where invfact i = invfacts M.! i
        invfacts = toMap $ reverse $ foldl' (\z i -> head z * inv M.! i `mod` k : z) [1] [1..maxN]
          where
            inv = foldl' step (M.fromList [(0,0),(1,1)]) [2..maxN]
              where step z i = M.insert i (k - ((k `div` i) * (z M.! (k `mod` i)) `mod` k)) z

findDup xs = step 0 (sort xs)
  where
    step i xs'
      | head xs' == head xs'' = head xs'
      | otherwise = step (i+1) xs''
      where xs'' = tail xs'

solve :: [[Int]] -> IO Integer
solve ((n:_):xs:_) = step 1
  where
    (a:b:_) = elemIndices (findDup xs) xs
    m = a + n - b
    step i
      | i > n+1 = return 0
      | i-1 > m = print (nCr (n+1) i) >> step (i+1)
      | otherwise = print ((nCr (n+1) i - nCr m (i-1)) `mod` k) >> step (i+1)

main = getContents >>= solve.map (map read . words).lines


{-# LANGUAGE MultiWayIf #-}

import Data.List

main :: IO ()
main = do
  [x,a,b] <- fmap (map read . words) getLine :: IO [Int]
  putStrLn $ if | b <= a     -> "delicious"
                | b <= x + a -> "safe"
                | otherwise  -> "dangerous"

Score : 100 points

Problem Statement

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier.
He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache.

Constraints

1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache.

Sample Input 1

4 3 6

Sample Output 1

safe

He ate the food three days after the "best-by" date. It was not delicious or harmful for him.

Sample Input 2

6 5 1

Sample Output 2

delicious

He ate the food by the "best-by" date. It was delicious for him.

Sample Input 3

3 7 12

Sample Output 3

dangerous

He ate the food five days after the "best-by" date. It was harmful for him.


import Control.Monad

push :: Int -> [Int] -> Int -> [Int] -> Bool
push 0 _ _ ps = 2 `elem` ps
push n bs b ps = let pushed = bs !! (b-1)
      in push (n-1) bs pushed (pushed:ps)

main :: IO ()
main = do
  n <- readLn :: IO Int
  bs <- replicateM n readLn :: IO [Int]
  print $ push n bs (head bs) []

Score : 200 points

Problem Statement

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up.
These buttons are numbered 1 through N.
When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It is possible that i=a_i.
When Button i is not lighten up, nothing will happen by pressing it.

Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

Print -1 if it is impossible to lighten up Button 2.
Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button 1, then Button 3.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

Pressing Button 1 lightens up Button 3, and vice versa, so Button 2 will never be lighten up.

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3


import Control.Monad

main :: IO ()
main = do
  n <- readLn :: IO Int
  bs <- replicateM n readLn :: IO [Int]
  let zs = zip [1..n] bs
  print $ access (head zs) zs []

access :: (Int, Int) -> [(Int, Int)] -> [Int] -> Int
access (_,v) zs acc =
  let (ni, nv) = head $ filter (\z -> (fst z) == v) zs
     in if nv == 2
           then
             length acc + 2
           else
             if any (==nv) acc
                then
                  -1
                else
                  access (ni, nv) zs (nv:acc)


main = do
  ns <- fmap (fmap (read :: String -> Int) . words) . lines <$> getContents
  let ls = concat $ tail ns
  putStrLn $ solve ls

solve :: [Int] -> String
solve ls
  | notElem 2 ls = "-1"
  | otherwise = show $ length $ takeWhile (/=2) ls


import Control.Monad
import Data.IntMap.Strict (IntMap, empty, insert, (!))

main = do
  n <- readLn
  print . g n n 1 . f 1 <$> replicateM n readLn

f _ [] = empty
f k (x:xs) = insert k x . f (k+1) $ xs

g n t x as
  | x == 2 = n - t
  | t < 0 = -1
  | otherwise = g n (t-1) (as ! x) as


import           Control.Monad
import qualified Data.ByteString.Char8       as BS
import           Data.Maybe
import qualified Data.Vector.Unboxed.Mutable as VM

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

main = do
  [n, m] <- getIntList

  let (x, y) = if n >= m then (n, m) else (m, n)
      p = 10^9 + 7 :: Int

  d <- VM.new (x+1)
  VM.set d (0::Int)

  let fac :: Int -> IO Int
      fac x | x == 1    = return 1
            | otherwise = do
                t <- VM.read d x
                if t > 0
                  then return t
                  else do fx_1 <- fac (x-1)
                          let r = x * fx_1 `mod` p
                          VM.write d x r
                          return r

      solve :: Int -> Int -> IO Int
      solve a b | a - b >= 2 = return 0
                | a - b == 1 = do fa <- fac a
                                  fb <- fac b
                                  return $ fa * fb `mod` p
                | otherwise  = do -- a == b
                    fa <- fac a
                    return $ fa * fa `mod` p * 2 `mod` p

  ans <- solve x y
  print ans

Score : 300 points

Problem Statement

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477


import Data.List
import qualified Data.IntMap.Strict as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

snub = S.toList . S.fromList
readInt = maybe undefined fst . B.readInt
untilFix f x = let x1 = f x in if x1 == x then x else untilFix f x1

kruskal n = kruskalDP n uf0 0 0
  where
    uf0 = fromDistinctAscList [1..n]

kruskalDP _ _ acc _ [] = acc
kruskalDP n uf acc x (((a,b),d):abd)
  | x == n = acc
  | same uf a b = kruskalDP n uf acc x abd
  | otherwise = kruskalDP n (merge uf a b) (acc + d) (succ x) abd

main = do
  getLine
  xys <- map ((\[x,y]->(x,y)) . map readInt . B.words) . B.lines <$> B.getContents
  let xyis = zip (snub xys) [1..]
  let xysx = sortOn fst xyis
  let xysy = sortOn (snd.fst) xyis
  print (built xysx xysy)

built xysx xysy = kruskal n edge
  where
    n = length xysx
    edge = sortOn snd (edgex ++ edgey)
    edgex = zipWith mkedge xysx (tail xysx)
    edgey = zipWith mkedge xysy (tail xysy)

mkedge ((xi,yi),i) ((xj,yj),j) = ((i,j), min (abs (xj-xi)) (abs (yj-yi)))

data UnionFind = UnionFind {tree :: M.IntMap Point, rk :: M.IntMap Rank}
type Point = Int
type Rank = Int

rep :: UnionFind -> Point -> Point
rep uf = (M.!) (tree uf)

rank :: UnionFind -> Point -> Rank
rank uf = (M.!) (rk uf)

merge :: UnionFind -> Point -> Point -> UnionFind
merge uf p1 p2
  | r1 /= r2 && rank uf r1 > rank uf r2 = UnionFind (M.insert p2 r1 (M.insert r2 r1 (tree uf))) (M.insert r1 (r1 + r2) (rk uf))
  | r1 /= r2 = UnionFind (M.insert p1 r2 (M.insert r1 r2 (tree uf))) (M.insert r2 (r1 + r2) (rk uf))
  | otherwise = uf
  where
    r1 = untilFix (rep uf) p1
    r2 = untilFix (rep uf) p2

same :: UnionFind -> Point -> Point -> Bool
same uf p1 p2 = untilFix (rep uf) p1 == untilFix (rep uf) p2

fromDistinctAscList :: [Point] -> UnionFind
fromDistinctAscList ps = UnionFind tree0 rk0
  where
    tree0 = M.fromDistinctAscList [(i,i) | i <- ps]
    rk0 = M.fromDistinctAscList [(i,1) | i <- ps]

Score : 500 points

Problem Statement

There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

2 ≤ N ≤ 10^5

0 ≤ x_i,y_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.

Sample Input 1

3
1 5
3 9
7 8

Sample Output 1

3

Build a road between Towns 1 and 2, and another between Towns 2 and 3. The total cost is 2+1=3 yen.

Sample Input 2

6
8 3
4 9
12 19
18 1
13 5
7 6

Sample Output 2

8


import qualified Data.Map as M
import Data.List

solve :: [[Int]] -> String
solve ((w:h:n:_):b)
  | stack == [0] = "YES"
  | otherwise = "NO"
  where
    edge x y = x == 0 || x == w || y == 0 || y == h
    clockwise a b = compare (toLiner a) (toLiner b)
      where toLiner (i,(x,y))
              | y == 0 = x
              | x == w = w + y
              | y == h = w + h + w - x
              | otherwise = w + h + w + h - y

    sortIndices l = map fst $ sortBy clockwise ps
      where ps = concatMap (\(i, x1:y1:x2:y2:_) -> [(i,(x1,y1)), (i,(x2,y2))]) $ zip [1..] l

    b' = sortIndices $ filter (\(x1:y1:x2:y2:_) -> edge x1 y1 && edge x2 y2) b
    stack = foldl' (\(z:zs) i -> if i /= z then i : z : zs else zs) [0] b'

main = getContents >>= putStrLn.solve.map (map read . words).lines

Score : 700 points

Problem Statement

Snuke is playing a puzzle game.
In this game, you are given a rectangular board of dimensions R × C, filled with numbers. Each integer i from 1 through N is written twice, at the coordinates (x_{i,1},y_{i,1}) and (x_{i,2},y_{i,2}).

The objective is to draw a curve connecting the pair of points where the same integer is written, for every integer from 1 through N.
Here, the curves may not go outside the board or cross each other.

Determine whether this is possible.

Constraints

1 ≤ R,C ≤ 10^8

1 ≤ N ≤ 10^5

0 ≤ x_{i,1},x_{i,2} ≤ R(1 ≤ i ≤ N)

0 ≤ y_{i,1},y_{i,2} ≤ C(1 ≤ i ≤ N)

All given points are distinct.

All input values are integers.

Input

Input is given from Standard Input in the following format:

R C N
x_{1,1} y_{1,1} x_{1,2} y_{1,2}
:
x_{N,1} y_{N,1} x_{N,2} y_{N,2}

Output

Print YES if the objective is achievable; print NO otherwise.

Sample Input 1

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

Sample Output 1

YES

The above figure shows a possible solution.

Sample Input 2

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

Sample Output 2

NO

Sample Input 3

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

Sample Output 3

YES

Sample Input 4

1 1 2
0 0 1 1
1 0 0 1

Sample Output 4

NO


--{-# LANGUAGE BangPatterns #-}
--{-# LANGUAGE ScopedTypeVariables #-}
--{-# LANGUAGE FlexibleContexts #-}
--{-# LANGUAGE ViewPatterns #-}
--{-# LANGUAGE OverloadedStrings #-}

import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map as MP
import qualified Data.Set as ST
import qualified Data.Sequence as SQ
import Data.Array
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.IO
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Char
import Data.Bits
import Data.List
import Data.Tuple
import Data.Functor
import Data.IORef
import Data.STRef
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Debug.Trace
-- import qualified Data.Vector.Algorithms.Merge as VAM
-- import qualified Data.Heap as HP
-- import Numeric.Extra
-- import Data.Tuple.Extra
-- import Data.List.Extra

--------------------------------------------------------------------------
solve xs c
    | null ys = 10^5
    | all (==c) xs = 0
    | otherwise = 1 + loop xs c ""
    where
        ys = elemIndices c xs
        loop :: String -> Char -> String -> Int
        loop [] c acc = solve acc c
        loop [_] _ acc = solve acc c
        loop (x:y:xs) c acc
            | x==c && y/=c = loop (y:xs) c (acc ++ [x])
            | x/=c && y==c = loop (y:xs) c (acc ++ [y])
            | x==c && y==c = loop (y:xs) c (acc ++ [y])
            | x/=c && y/=c = loop (y:xs) c (acc ++ [x])

main = do
    xs <- str
    print $ minimum [solve xs c | c<-['a'..'z']]
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = BC.getLine >>= return . bsToInt

double :: IO Double
double = BC.getLine >>= return . bsToDouble

str :: IO String
str = getLine

strBS :: IO BC.ByteString
strBS = BC.getLine

-- convert
bsToInt :: BC.ByteString -> Int
bsToInt = fst . fromJust . BC.readInt

bsToDouble :: BC.ByteString -> Double
bsToDouble = read . BC.unpack

bsToIntTuple :: BC.ByteString -> (Int, Int)
bsToIntTuple bs = (a,b)
    where
        Just (a,bs') = parseInt bs
        Just (b,_) = parseInt bs'

bsToIntTriple :: BC.ByteString -> (Int, Int, Int)
bsToIntTriple bs = (a,b,c)
    where
        Just (a,bs') = parseInt bs
        Just (b,bs'') = parseInt bs'
        Just (c,_) = parseInt bs''

parseInt :: BC.ByteString -> Maybe (Int, BC.ByteString)
parseInt = BC.readInt . BC.dropWhile isSpace

-- single line
fromSLineL :: (BC.ByteString -> a) -> IO [a]
fromSLineL f = strBS >>= return . map f . BC.words

-- from single line to List / VU.Vector
sLineToIntL :: IO [Int]
sLineToIntL = fromSLineL bsToInt

sLineToDoubleL :: IO [Double]
sLineToDoubleL = fromSLineL bsToDouble

sLineToStrL :: IO [String]
sLineToStrL = fromSLineL BC.unpack

sLineToStrBSL :: IO [BC.ByteString]
sLineToStrBSL = fromSLineL id

sLineToIntV :: Int -> IO (VU.Vector Int)
sLineToIntV n = BC.getLine >>= return . VU.unfoldrN n parseInt

sLineToDoubleV :: IO (VU.Vector Double)
sLineToDoubleV = BC.getLine >>= return . VU.fromList . map bsToDouble . BC.words

-- multiple lines
fromMLinesL :: Int -> (BC.ByteString -> a) -> IO [a]
fromMLinesL n f = replicateM n (strBS >>= return . f)

fromMLinesV :: VU.Unbox a => Int -> (BC.ByteString -> a) -> IO (VU.Vector a)
fromMLinesV n f = VU.replicateM n (strBS >>= return . f)

-- from multiple lines to List / VU.Vector
mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = fromMLinesL n bsToInt

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = fromMLinesL n bsToDouble

mLinesToStrL :: Int -> IO [String]
mLinesToStrL n = fromMLinesL n BC.unpack

mLinesToStrBSL :: Int -> IO [BC.ByteString]
mLinesToStrBSL n = fromMLinesL n id

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = fromMLinesL n bsToIntTuple

mLinesToTripleL :: Int -> IO [(Int, Int, Int)]
mLinesToTripleL n = fromMLinesL n bsToIntTriple

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = fromMLinesV n bsToInt

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = fromMLinesV n bsToDouble

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = fromMLinesV n bsToIntTuple

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = fromMLinesV n bsToIntTriple

-- output
yesnoL :: Bool -> IO ()
yesnoL cond
    | cond = putStrLn "Yes"
    | otherwise = putStrLn "No"

yesnoU :: Bool -> IO ()
yesnoU cond
    | cond = putStrLn "YES"
    | otherwise = putStrLn "NO"

-- others
strToChr :: String -> Char
strToChr [x] = x

chrToStr :: Char -> String
chrToStr x = [x]

m1 :: Int -> Int
m1 x = subtract 1 x

toDouble :: Int -> Double
toDouble x = fromIntegral x

toInt :: Double -> Int
toInt x = floor x

Score : 300 points

Problem Statement

Snuke can change a string t of length N into a string t' of length N - 1 under the following rule:

For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.

There is a string s consisting of lowercase English letters.
Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same.
Find the minimum necessary number of operations.

Constraints

1 ≤ |s| ≤ 100

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum necessary number of operations to achieve the objective.

Sample Input 1

serval

Sample Output 1

3

One solution is: serval → srvvl → svvv → vvv.

Sample Input 2

jackal

Sample Output 2

2

One solution is: jackal → aacaa → aaaa.

Sample Input 3

zzz

Sample Output 3

0

All the characters in s are the same from the beginning.

Sample Input 4

whbrjpjyhsrywlqjxdbrbaomnw

Sample Output 4

8

In 8 operations, he can change s to rrrrrrrrrrrrrrrrrr.


import Data.Char (chr,ord)
import Data.Maybe (fromJust,isJust)

trans [] _ = []
trans [_] _ = []
trans (x:y:s) c
  | y == c = y:trans (y:s) c
  | otherwise = x:trans (y:s) c

solve :: String -> Int -> Char -> Int
solve s n c =
  if s == replicate (length s) c
    then n
    else
      solve ns (n+1) c
  where ns = trans s c

main = do
  s <- getLine :: IO String
  print $ minimum $ map (solve s 0.chr) [ord 'a'..ord 'z']


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

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

main = do
  xs <- readInts <$> BS.getLine
  format (mapM_ putInts) $ solve xs

solve :: [Int] -> Maybe [[Int]]
solve [hm, wm, h, w] =
  if hm `mod` h == 0 || wm `mod` w == 0
    then Nothing
    else Just [[f i j | i <- [1..wm]] | j <- [1..hm]]
      where
        f i j = if i `mod` w == 0 && j `mod` h == 0
          then - w * h
          else 1
--  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --

getInt1 :: IO Int
getInt1 = readInt1 <$> BS.getLine

getInt2 :: IO (Int, Int)
getInt2 = readInt2 <$> BS.getLine

getInt3 :: IO (Int, Int, Int)
getInt3 = readInt3 <$> BS.getLine

getInts :: IO [Int]
getInts = readInts <$> BS.getLine

getIntN :: Int -> IO [Int]
getIntN n = map readInt1 <$> replicateM n BS.getLine

format :: Show a => (a -> IO ()) -> Maybe a -> IO ()
format _ Nothing = putStrLn "No"
format f (Just a) = putStrLn "Yes" >> f a

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

-- if not applying, use "id"

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

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

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

Score : 700 points

Problem Statement

You are given four integers: H, W, h and w (1 ≤ h ≤ H, 1 ≤ w ≤ W).
Determine whether there exists a matrix such that all of the following conditions are held, and construct one such matrix if the answer is positive:

The matrix has H rows and W columns.

Each element of the matrix is an integer between -10^9 and 10^9 (inclusive).

The sum of all the elements of the matrix is positive.

The sum of all the elements within every subrectangle with h rows and w columns in the matrix is negative.

Constraints

1 ≤ h ≤ H ≤ 500

1 ≤ w ≤ W ≤ 500

Input

Input is given from Standard Input in the following format:

H W h w

Output

If there does not exist a matrix that satisfies all of the conditions, print No.

Otherwise, print Yes in the first line, and print a matrix in the subsequent lines in the following format:

a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}

Here, a_{ij} represents the (i,\ j) element of the matrix.

Sample Input 1

3 3 2 2

Sample Output 1

Yes
1 1 1
1 -4 1
1 1 1

The sum of all the elements of this matrix is 4, which is positive.
Also, in this matrix, there are four subrectangles with 2 rows and 2 columns as shown below. For each of them, the sum of all the elements inside is -1, which is negative.

Sample Input 2

2 4 1 2

Sample Output 2

No

Sample Input 3

3 4 2 3

Sample Output 3

Yes
2 -5 8 7
3 -5 -4 -5
2 1 -1 7


import qualified Data.ByteString.Char8 as B
import Data.Maybe
main=print.solve.map(fst.fromJust.B.readInt).B.words=<<B.getContents
solve(_:xs)=maximum xs-minimum xs

Score : 200 points

Problem Statement

It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.

There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.

Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.

Constraints

1 ≤ N ≤ 100

0 ≤ a_i ≤ 1000

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum distance to be traveled.

Sample Input 1

4
2 3 7 9

Sample Output 1

7

The travel distance of 7 can be achieved by starting at coordinate 9 and traveling straight to coordinate 2.

It is not possible to do with a travel distance of less than 7, and thus 7 is the minimum distance to be traveled.

Sample Input 2

8
3 1 4 1 5 9 2 6

Sample Output 2

8

There may be more than one house at a position.


import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.List
main=print.solve.sort.tail.map(fst.fromJust.B.readInt).B.words=<<B.getContents
solve(x:xs)=last xs-x


import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import qualified Data.ByteString.Char8 as C
import Debug.Trace
import Data.List
import Control.Monad
import Data.Ord
import qualified Data.IntSet as IS

r :: Int -> IO (U.Vector Int)
r n = U.unfoldrN n (C.readInt . C.dropWhile (==' ')) <$> C.getLine

r' :: IO [Int]
r'  =   unfoldr    (C.readInt . C.dropWhile (==' ')) <$> C.getLine

rp :: IO (Int,Int)
rp  = toTup . unfoldr    (C.readInt . C.dropWhile (==' ')) <$> C.getLine

toTup [a,b] = (a,b)

main :: IO ()
main = do
    n <- readLn
    as <- U.map (`div` 400) <$> r n
    let free = U.length $ U.filter (>=8) as
    let rest = IS.size $ IS.fromList $ U.toList $ U.filter (<8) as
    putStrLn $
        show (max 1 rest)
        ++ " "
        ++ (show $ min 8 (rest+free) )

Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


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

main :: IO ()
main = do
    _ <- fst . fromJust . B.readInt <$> B.getLine
    as <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    let (bs, cs) = partition (< 3200) as
        c = length $ nub $ map (`div` 400) bs
        t = if null cs then 0 else 1
    putStrLn $ show (max (t - c) c) ++ " " ++ show (min (c + length cs) 8)


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

main :: IO ()
main = do
    _ <- fst . fromJust . B.readInt <$> B.getLine
    as <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    let (bs, cs) = partition (< 3200) as
        c  = length $ nub $ map (`div` 400) bs
        t  = length cs
    putStrLn $ show (min (t `div` c + c) c) ++ " " ++ show (min (c + t) 8)


-- Try AtCoder
-- author: Leonardone @ NEETSDKASU

import Data.List

main = putStrLn . unwords . map show . solve . map read . tail . words =<< getContents

solve s = [mincolors, maxcolors] where
    (lowers, highers) = partition (< 8) $ map (`div` 400) s
    mincolors = length $ nub lowers
    maxcolors = mincolors + length highers


main=do
 n<-readLn;s<-getLine
 putStrLn(g s (f "" s 0 n))
  where f ini _ _ 0 = ini
        f ini las _ 1 = ini++las
        f _ ('(':')':las) 0 lan = f "" las 0 (lan-2)
        f ini ('(':')':las) inn lan = f (init ini) ((last ini):las) (inn-1) (lan-1)
        f ini las inn lan = f (ini++[head las]) (tail las) (inn+1) (lan-1)
        g s l = ['('|x<-l,x==')']++s++[')'|x<-l,x=='(']

Score : 400 points

Problem Statement

You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:

() is a correct bracket sequence.

If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.

If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))


import Control.Applicative
import Control.Monad
import Data.List
import Data.Char
strToInt s = (read :: String -> Int) s

main :: IO ()
main = do
    -- 文字列の入力
    n <- getLine
    s <- getLine
    let diff = foldl (\acc c -> if c == '(' then succ acc else pred acc) 0 s
    if diff == 0
        then putStrLn s
        else if diff > 0
            then putStrLn $ s ++ replicate diff ')'
            else putStrLn $ replicate (abs diff) '(' ++ s


main = interact $ (\[a,b] -> if a+b>=10 then "error" else show (a+b)) . fmap read . words

Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


main = do
  [a,b] <- map read . words <$> getLine
  putStrLn $ if a+b < 10 then show (a+b) else "error"


main::IO()
main=do
  abc<-getLine
  let a:b:[]=map read (words abc)::[Int]
  case ((a+b)< 10) of
    True -> print (a+b)
    False-> putStr "error\n"


f [] = True
f (c : s) = (not $ or $ map (== c) s) && f s

main = do
  s <- getLine
  if f s
    then putStrLn "yes"
    else putStrLn "no"

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.

Constraints

2 ≤ |S| ≤ 26, where |S| denotes the length of S.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If all the characters in S are different, print yes (case-sensitive); otherwise, print no.

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes


import Control.Monad
import Data.List

main = do
  n <- readLn :: IO Int
  xs <- replicateM n readLn :: IO [Int]
  let s = solve xs
  print $ if s `mod` 10 == 0 then 0 else s

solve :: [Int] -> Int
solve [] = 0
solve xs =
  let
    ts = filter (flip elem [0,10..100]) xs
    nts = filter (flip notElem [0,10..100]) xs
  in
    sum ts + trim nts
  where
    trim :: [Int] -> Int
    trim [] = 0
    trim xs
      | sum xs `mod` 10 == 0 = trim (delete (minimum xs) xs)
      | otherwise = sum xs

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.


import qualified Data.Vector.Unboxed as VU
import Data.Bits
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.List

-- 1 <= damageOther < damageTarget <= 10^9
isPossibleWith :: VU.Vector Int -> Int -> Int -> Int -> Bool
isPossibleWith hps damageTarget damageOther numMagics
  = (<= numMagics) $ VU.sum
    $ VU.map (\hp -> max 0 $ (hp - damageMin + damageDiff - 1) `div` damageDiff)
    $ hps
  where
    damageMin = damageOther * numMagics
    damageDiff = damageTarget - damageOther

query :: VU.Vector Int -> Int -> Int -> Int
query hps damageTarget damageOther = binSearch 0 (10 ^ 9 * VU.length hps)
  where
    binSearch ng ok
      | ok - ng <= 1 = ok
      | isPossibleWith hps damageTarget damageOther mid = binSearch ng mid
      | otherwise = binSearch mid ok
      where
        mid = (ng + ok) `shiftR` 1

main :: IO ()
main = do
  [n, damageTarget, damageOther]
    <- unfoldr (BS.readInt . BS.dropWhile (==' ')) <$> BS.getLine
  hps <- VU.unfoldrN n (BSL.readInt . BSL.dropWhile (`elem` "\n\r"))
         <$> BSL.getContents
  print $ query hps damageTarget damageOther

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.

Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows:

Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by A, and the health of each of the other monsters will decrease by B. Here, A and B are predetermined parameters, and A > B holds.

At least how many explosions do you need to cause in order to vanish all the monsters?

Constraints

All input values are integers.

1 ≤ N ≤ 10^5

1 ≤ B < A ≤ 10^9

1 ≤ h_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N A B
h_1
h_2
:
h_N

Output

Print the minimum number of explosions that needs to be caused in order to vanish all the monsters.

Sample Input 1

4 5 3
8
7
4
2

Sample Output 1

2

You can vanish all the monsters in two explosion, as follows:

First, cause an explosion centered at the monster with 8 health. The healths of the four monsters become 3, 4, 1 and -1, respectively, and the last monster vanishes.

Second, cause an explosion centered at the monster with 4 health remaining. The healths of the three remaining monsters become 0, -1 and -2, respectively, and all the monsters are now vanished.

Sample Input 2

2 10 4
20
20

Sample Output 2

4

You need to cause two explosions centered at each monster, for a total of four.

Sample Input 3

5 2 1
900000000
900000000
1000000000
1000000000
1000000000

Sample Output 3

800000000


groupcheck::Int->Int->String
groupcheck x y
    |elem x a && elem y a = "Yes"
    |elem x b && elem y b = "Yes"
    |elem x c && elem y c = "Yes"
    |otherwise = "No"
    where
        a = [1,3,5,7,8,10,12]
        b = [4,6,9,11]
        c = [2]

main::IO ()
main = do
    [a,b] <- map read . words <$> getLine::IO[Int]
    putStrLn $ groupcheck a b

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No


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

readInts = map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine

main = do
  xy <- readInts
  if or $ map (\c -> and $ map (flip elem c) xy) cs
    then putStr "Yes\n"
    else putStr "No\n"
    where
      cs = [[1, 3, 5, 7, 8, 10, 12],
            [4, 6, 9, 11],
            [2]]


solve :: Int -> Int -> String
solve x y
  | x `elem` [1,3,5,7,8,10,12] = if y `elem` [1,3,5,7,8,10,12] then "Yes" else "No"
  | x `elem` [4,6,9,11] = if y `elem` [4,6,9,11] then "Yes" else "No"
  | x `elem` [2] = if y `elem` [2] then "Yes" else "No"

main = do
  [x,y] <- fmap read <$> words <$> getLine :: IO[Int]
  putStrLn $ solve x y


main = do
  [x, y] <- map read . words <$> getLine
  putStr $ f x y

a = [1, 3, 5, 8, 10, 12]
b = [4, 6, 9, 11]
c = [2]

f x y
  | elem x a && elem y a = "Yes"
  | elem x b && elem y b = "Yes"
  | elem x c && elem y c = "Yes"
  | otherwise = "No"


import Data.List

main = do
  [h, w] <- map read . words <$> getLine :: IO [Int]
  let ws = map (solve h w) [1..w-1]
      hs = map (solve w h) [1..h-1]
  print $ min (minimum ws) (minimum hs)

solve :: Int -> Int -> Int -> Int
solve h w wa = let wb = (w - wa) `div` 2
                   x = wa * h
                   y1 = wb * h
                   z1 = (w - wa - wb) * h
                   y2 = (w - wa) * (h `div` 2)
                   z2 = (w - wa) * ((-) h $ h `div` 2)
                   mi1 = minimum [x, y1, z1]
                   ma1 = maximum [x, y1, z1]
                   mi2 = minimum [x, y2, z2]
                   ma2 = maximum [x, y2, z2]
               in if w - wa >= 2 then min (ma1 - mi1) (ma2 - mi2)
                                 else ma2 - mi2

Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


import Data.List

main = do
  [h, w] <- sort . map read . words <$> getLine :: IO [Int]
  let [w1, w2] = split w
  if mod h 3 == 0 || mod w 3 == 0
    then print 0
    else print $ abs $ w1 * h - w2 * (h `div` 2)

split :: Int -> [Int]
split w
  | mod w 3 == 2 = let x = div w 3
                   in [x+1, w-x-1]
  | otherwise    = [div w 3, w - (div w 3)]


main = do
  [h, w] <- sort . map read . words <$> getLine
  print $ solve h w

solve h w
  | h `mod` 3 == 0 = 0
  | w `mod` 3 == 0 = 0
  | even h = h `div` 2
  | even w = w `div` 2
  | otherwise = h `div` 2 + w `div` 3 + 1

sort [x, y]
  | x > y = [y, x]
  | otherwise = [x, y]


main::IO ()
main = do
    [a,b,c] <- map read . words <$> getLine::IO[Int]
    putStrLn $ if c>=a && c<=b then "Yes" else "No"

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


main :: IO ()
main = do
  [a, b, c] <- (map read . words) <$> getLine :: IO [Int]
  putStrLn $ if a <= c && c <= b then "Yes" else "No"


module Main where

import Data.List

main :: IO ()
main = do
    [a, b, c] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ if a <= c && c <= b then "Yes" else "No"


import Control.Monad
import Data.List
f s n=length(filter(==n)s)
main=do
 [n,m]<-map read.words<$>getLine
 s<-replicateM m (map read.words<$>getLine)
 mapM_ print$map (f (concat s)) [1..n]

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values 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 in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

8 8
1 2
3 4
1 5
2 8
3 7
5 2
4 1
6 8

Sample Output 3

3
3
2
2
2
1
1
2


main :: IO ()
main = do
  [n, m] <- map read . words <$> getLine
  cs <- map read . words <$> getContents
  sequence_ [print $ length $ filter (== i) cs | i <- [1..n] ]


import Control.Monad
import Data.Array
main = do
  [n,m] <- map read . words <$> getLine
  abs <- replicateM m $ map read . words <$> getLine
  let ar = accumArray (+) 0 (1,n) [(i,1) | ab <- abs, i <- ab]
  mapM_ print $ elems $ ar


import Control.Monad
import Control.Monad.ST
import qualified Data.ByteString.Char8 as C
import Data.List
import Data.Maybe
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM

main = sol <$> get >>= print

get = fmap (unfoldr (C.readInt . C.dropWhile (==' '))) . C.lines <$> C.getContents

sol ([_,k]:ab) = fromJust . U.findIndex (k<=) . U.scanl1' (+) $ runST $ do
  v <- UM.replicate (1+10^5 :: Int) (0 :: Int)
  forM_ ab $ \[a,b] -> UM.modify v (+b) a
  U.freeze v

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


import Control.Monad
import Data.List

solve :: Int -> [(Int, Int)] -> Int
solve k ((a, b):rs)
  | k <= b = a
  | True = solve (k - b) rs

main :: IO ()
main = do
  n:k:_ <- fmap (\x -> read x :: Int) <$> words <$> getLine
  l <- fmap ((\[a, b] -> (a, b)) . (fmap (\x -> read x :: Int)) . words) <$> replicateM n getLine
  print $ solve k $ sort l


import Control.Monad
import Control.Monad.Primitive (PrimState)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)

main :: IO ()
main = do
    [n, k] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    mv <- MV.replicate 100002 0 :: IO (MV.MVector (PrimState IO) Int)
    replicateM_ n $ do
        [a, b] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
        MV.unsafeModify mv (+ b) (a - 1)
    v <- V.unsafeFreeze mv
    print $ fromJust $ V.findIndex (>= k) (V.scanl' (+) 0 v)


import Control.Monad
import Control.Monad.Primitive (PrimState)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)

main :: IO ()
main = do
    [n, k] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    mv <- MV.replicate (k + 1) 0 :: IO (MV.MVector (PrimState IO) Int)
    replicateM_ n $ do
        [a, b] <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
        MV.unsafeModify mv (+ b) (a - 1)
    v <- V.freeze mv
    print $ fromJust $ V.findIndex (>= k) (V.scanl (+) 0 v)


import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Map as Map
import Data.Array
import qualified Data.ByteString.Char8 as BC
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Sequence as Sq
import qualified Data.IntMap as IMap
import qualified Data.Vector as V
import Data.Sequence (ViewL(..),ViewR(..),(><),(<|),(|>),Seq)

bsreadInt :: BC.ByteString -> Int
bsreadInt = fst . fromJust . BC.readInt

sqleft :: Seq a -> a
sqleft q = sqleft_(Sq.viewl q)
sqleft_ :: ViewL a -> a
sqleft_ (x :< xs) = x
sqright :: Seq a -> a
sqright q = sqright_(Sq.viewr q)
sqright_ :: ViewR a -> a
sqright_ (xs :> x) = x

-------------------------------------------------------------
count :: [[Int]] -> Int -> Int -> Int
count (c:cn) n k = if (n + b) >= k
                   then a
                   else count cn (n+b) k
                   where a = c !! 0
                         b = c !! 1

main = do
    [n,k] <- map bsreadInt . BC.words <$> BC.getLine
    abin <- map ((map bsreadInt . BC.words)) <$> replicateM n BC.getLine
    let ab = sort abin
    print $ count ab 0 k


import Data.List
import Control.Monad

main = do
    [n, k] <- map read . words <$> getLine
    abss <- replicateM n $ map read . words <$> getLine
    print . getIndex k . map sumSnd $ groupByHead abss

groupByHead = groupBy (\x y -> head x == head y) . sort
sumSnd xs =  [head $ head xs, sum $ map (last) xs]
getIndex k (x:xs) = if last x >= k
                    then head x
                    else getIndex (k - last x) xs


solve :: [Integer] -> Integer -> Integer -> Integer -> Integer
solve [] _ _ acc = acc
solve (x:xs) end_of_water t acc
  | end_of_water <= x = solve xs (x+t) t (acc+t)
  | otherwise          = solve xs (x + t) t (acc - (end_of_water - x) + t)

main = do
     nt <- words <$> getLine
     let n = read $ (nt !! 0) :: Integer
     let t = read $ (nt !! 1) :: Integer
     -- putStrLn $ show $ n
     -- putStrLn $ show $ t

     ts_str <- words <$> getLine
     let ts = map (\s -> read s :: Integer) ts_str
     let ans = solve ts 0 t 0
     putStrLn $ show $ ans
     return ()

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


main :: IO ()
main = do
    [a,b,c] <- map read . words <$> getLine :: IO [Int]
    let ret = c `elem` [a * i `rem` b | i <- [1..b]]
    putStrLn $ if ret then "YES" else "NO"

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


main :: IO ()
main = do
    [a,b,c] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ if c `mod` gcd a b == 0 then "YES" else "NO"


main = do
  [a,b,c] <- map read . words <$> getLine
  let f x ys = x==c || elem x ys && f ((x+a)`mod`b) (x:ys)
  putStrLn $ if f (a`mod`b) [] then "YES" else "NO"


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

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

solve :: Int -> [Int] -> Int
solve time [t] = time
solve time (t1:t2:ts) = result + solve time (t2:ts)
  where result = min time $ t2 - t1

main :: IO ()
main = do
  [n, t] <- map read . words <$> getLine
  ss <- readIntsLine
  print $ solve t ss

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67