Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


import Control.Applicative

main = getLine >>= putStrLn.show.maximum.f.read
f v = filter (<=v) [x^y | x <- [1..32], y <- [1..32]]

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

Submitted source-code file size, in bytes.

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

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


perfectPower :: Integer -> [Integer]
perfectPower x = 1 : do
  b <- [2 .. x]
  return $ b ^ floor (logBase (fromIntegral b) (fromIntegral x))

solve :: Integer -> Integer
solve x = maximum $ filter (<= x) $ perfectPower x

main :: IO ()
main = do
  x <- read <$> getLine
  print . solve $ x


perfectPower :: Integer -> [Integer]
perfectPower x = 1 : do
  b <- [2 .. x]
  return $ b ^ floor (logBase (fromIntegral b) (fromIntegral x))

solve :: Integer -> Integer
solve x = maximum $ perfectPower x

main :: IO ()
main = do
  x <- read <$> getLine
  print . solve $ x


perfectPower :: Int -> [Int]
perfectPower x = 1 : do
  b <- [2 .. floor $ sqrt $ fromIntegral x]
  return $ b ^ floor (logBase (fromIntegral b) (fromIntegral x))

solve :: Int -> Int
solve x = maximum $ perfectPower x

main :: IO ()
main = do
  x <- read <$> getLine
  print . solve $ x


import Data.Graph
import qualified Data.Vector.Unboxed as U
import qualified Data.Set as S
import qualified Data.Foldable as F
import Data.List
import Control.Monad
import qualified Data.ByteString.Char8 as B

solve n m p e = sum $ map count $ cmps where
  count cmp = S.size $ S.intersection (S.fromList cmp) $
    S.fromList [ p U.! (i-1) | i <- cmp ]
  cmps = map F.toList $ components $ buildG (1,n) e

main = do
  [n, m] <- readInts
  p <- U.fromList <$> readInts
  e <- replicateM m $ (\[a,b]->(a,b)) <$> readInts
  print $ solve n m p e

readInts = unfoldr (B.readInt . B.dropWhile (== ' '))
  <$> B.getLine

Score : 400 points

Problem Statement

We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N.
We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M).
AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized:

Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}.

Find the maximum possible number of i such that p_i = i after operations.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

p is a permutation of integers from 1 through N.

1 ≤ x_j,y_j ≤ N

x_j ≠ y_j

If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
p_1 p_2 .. p_N
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the maximum possible number of i such that p_i = i after operations.

Sample Input 1

5 2
5 3 1 4 2
1 3
5 4

Sample Output 1

2

If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2.

Sample Input 2

3 2
3 2 1
1 2
2 3

Sample Output 2

3

If we perform the operation by, for example, choosing j=1, j=2, j=1 in this order, p becomes 1 2 3, which is obviously optimal.
Note that we may choose the same j any number of times.

Sample Input 3

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

Sample Output 3

8

Sample Input 4

5 1
1 2 3 4 5
1 5

Sample Output 4

5

We do not have to perform the operation.


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

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

main = do
    [a,b] <- getIntList
    print $ if b < a then a-1 else a

Score: 100 points

Problem Statement

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.

For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.

How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

a is an integer between 1 and 12 (inclusive).

b is an integer between 1 and 31 (inclusive).

2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Sample Input 1

5 5

Sample Output 1

5

There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.

Sample Input 2

2 1

Sample Output 2

1

There is only one day that is Takahashi: 1-1.

Sample Input 3

11 30

Sample Output 3

11

There are eleven days that are Takahashi: 1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 9-9, 10-10 and 11-11.


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import qualified Data.ByteString.Char8 as BC
import           Data.Maybe            (fromJust)

main :: IO ()
main = do
  [a, b] <- map readInt . BC.words <$> BC.getLine
  print $ solve a b

solve :: Int -> Int -> Int
solve a b
  | a <= b    = a
  | otherwise = a - 1

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


module Main where

import Control.Applicative

main = do
 [a, b] <- map (read::String -> Int) . words <$> getLine
 if b < a then print (a - 1) else print a


main = do
    a <- map read . words <$> getLine :: IO [Int]
    k <- readLn
    let m = maximum a
    print $ sum a - m + m * 2 ^ k

Score: 200 points

Problem Statement

There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:

Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.

What is the largest possible sum of the integers written on the blackboard after K operations?

Constraints

A, B and C are integers between 1 and 50 (inclusive).

K is an integer between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C
K

Output

Print the largest possible sum of the integers written on the blackboard after K operations by E869220.

Sample Input 1

5 3 11
1

Sample Output 1

30

In this sample, 5, 3, 11 are initially written on the blackboard, and E869120 can perform the operation once.

There are three choices:

Double 5: The integers written on the board after the operation are 10, 3, 11.

Double 3: The integers written on the board after the operation are 5, 6, 11.

Double 11: The integers written on the board after the operation are 5, 3, 22.

If he chooses 3., the sum of the integers written on the board afterwards is 5 + 3 + 22 = 30, which is the largest among 1. through 3.

Sample Input 2

3 3 4
2

Sample Output 2

22

E869120 can perform the operation twice. The sum of the integers eventually written on the blackboard is maximized as follows:

First, double 4. The integers written on the board are now 3, 3, 8.

Next, double 8. The integers written on the board are now 3, 3, 16.

Then, the sum of the integers eventually written on the blackboard is 3 + 3 + 16 = 22.


import Control.Arrow
import Data.Bits
import Data.Char
import Data.List

main :: IO ()
main = do
  xs <- getInts
  k <- getInt
  let m = maximum xs
  print $ sum xs + m * (2 ^ k - 1)

getInt :: IO Int
getInt = readLn

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


import qualified Data.Vector as V

main :: IO ()
main = do
  [h,w] <- map read . words <$> getLine
  t <- getTable h
  putStrLn $ if solve t h w then "Yes" else "No"

getTable :: Int -> IO Table
getTable h = V.replicateM h $ (V.fromList . map toBW) <$> getLine
  where toBW '#' = B
        toBW '.' = W
        toBW _ = error "!"

solve :: Table -> Int -> Int -> Bool
solve tbl w h = all check [(i,j) | j <- [0..(h-1)], i <- [0..(w-1)]]
  where
    get (i,j) = tbl V.! j V.! i
    around (x,y) | x == 0 && y == 0 = [(1,0),(0,1)]
                 | x == 0 && y == h-1 = [(x,y-1),(x+1,y)]
                 | x == w-1 && y == 0 = [(x-1,y),(x,y+1)]
                 | x == w-1 && y == h-1 = [(x-1,y),(x,y-1)]
                 | x == 0 = [(x,y-1),(x,y+1),(x+1,y)]
                 | x == w-1 = [(x,y-1),(x,y+1),(x-1,y)]
                 | y == 0 = [(x-1,y),(x+1,y),(x,y+1)]
                 | y == h-1 = [(x-1,y),(x+1,y),(x,y-1)]
                 | otherwise = [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
    check i | get i == W = True
            | otherwise = any (==B) [get n | n <- around i]

data BW = B | W deriving Eq

type Table = V.Vector (V.Vector BW)

Score: 300 points

Problem Statement

We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, j}= #, and to make Square (i, j) white when s_{i, j}= ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

H is an integer between 1 and 50 (inclusive).

W is an integer between 1 and 50 (inclusive).

For every (i, j) (1 \leq i \leq H, 1 \leq j \leq W), s_{i, j} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}
s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}
: :
s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

5 5
#.#.#
.#.#.
#.#.#
.#.#.
#.#.#

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes


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

getLineN :: Int -> IO [String]
getLineN n = replicateM n getLine

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

main = do
    [h,w] <- getNumList
    canvas <- getLineN h
    putStrLn.judge $ evaluate canvas h w

evaluate cs h w = all (== True) $ map f [(x,y) | x <- [0..h-1], y <- [0..w-1]] where
    f (x,y) = if cs .!! (x,y) == '.' then True else any (\pos -> cs .!! pos == cs .!! (x,y)) [(x-1,y),(x+1,y),(x,y+1),(x,y-1)]
    (.!!) cs (x,y) = if (x < 0 || x >= h || y < 0 || y >= w) then 'a' else (cs !! x) !! y

judge True = "Yes"
judge False = "No"


import qualified Data.IntMap as M
import           Data.List

main :: IO ()
main = do
  getLine
  as <- map read . words <$> getLine
  print $ solve as

solve :: [Int] -> Int
solve = M.foldl' (+) 0
    . fmap (\x -> x * (x - 1) `div` 2)
    . foldl' (\mp x -> M.insertWith (+) x 1 mp) (M.singleton 0 0)
    . scanl' (+) 0

Score : 200 points

Problem Statement

We have an integer sequence A, whose length is N.

Find the number of the non-empty contiguous subsequences of A whose sums are 0.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

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

-10^9 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the number of the non-empty contiguous subsequences of A whose sum is 0.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are 0: (1,3,-4), (-4,2,2) and (2,-2).

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of (1, -1) are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


import Data.List
main=getLine*>getLine>>=print.sum.map ((\a->(a*a-a)`div`2).length).group.sort.scanl' (+) 0.map read.words


import qualified Data.IntMap as M
import qualified Data.ByteString.Lazy.Char8 as B
import Data.List
import Debug.Trace
import Test.QuickCheck

main = do
  _ <- getLine
  input <- B.getContents
  let as = map readInt . B.words $ input
  print (solve as)

readInt :: B.ByteString -> Int
readInt s = case B.readInt s of Just (n,_) -> n

solve :: [Int] -> Int
solve xs =
  length [1|ys <- tails xs, not (null ys), y <-scanl1 (+) ys, y==0]


isgood :: Int -> Int -> [[Char]] -> Bool
isgood a b xs = foldr (&&) True [sec!!j!!i == sec!!i!!j | j <- [0..len], i <- [0..len]]
    where
      len = (length xs) - 1
      sec = [[xs!!(mod (i+a) (len+1))!!(mod (j+b) (len+1)) | j <- [0..len]] | i <- [0..len]]

solve :: [[Char]] -> Int
solve xs = sum $ [1 | a <- [0..len], b <- [0..len], isgood a b xs]
    where
      len = (length xs) - 1

transform :: [String] -> [[Char]]
transform (_:xs) = xs

main :: IO ()
main = print . solve . transform . words =<< getContents

Score : 500 points

Problem Statement

Snuke has two boards, each divided into a grid with N rows and N columns.
For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

First, choose two integers A and B ( 0 \leq A, B < N ).

Write one letter in each square on the second board.
Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board.
Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

1 \leq N \leq 300

S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Sample Input 1

2
ab
ca

Sample Output 1

2

For each pair of A and B, the second board will look as shown below:

The second board is a good board when (A,B) = (0,1) or (A,B) = (1,0), thus the answer is 2.

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

Every possible choice of A and B makes the second board good.

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

No possible choice of A and B makes the second board good.


module Main (main) where

import qualified Data.ByteString.Char8 as C8
import Data.Bool

main :: IO ()
main = do
  [s] <- readStrings
  print . showAnswer $ solve s

type Input  = (String)
type Output = Int

solve :: Input -> Output
solve = (700+) . (100*) . length . filter (=='o')

showAnswer :: Output -> Answer
showAnswer = Number

-- utils
readStrings :: IO [String]
readStrings = map C8.unpack . C8.words <$> C8.getLine

data Answer
  = YesNo Bool
  | YESNO Bool
  | AB Bool
  | Number Int
  | String String
  | Compare Ordering
  | Compare2 Ordering

instance Show Answer where
  show (YesNo b)    = bool "No" "Yes" b
  show (YESNO b)    = bool "NO" "YES" b
  show (AB b)       = bool "B"  "A" b
  show (Number i)   = show i
  show (String s)   = s
  show (Compare o)  = ordering "<" "=" ">" o
  show (Compare2 o) = ordering "Right" "Balanced" "Left" o

ordering :: a -> a -> a -> Ordering -> a
ordering lt eq gt o = case o of
  LT -> lt
  EQ -> eq
  GT -> gt

Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


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

price
  :: String -> Int
price s = 700 + 100*os
  where
    os = length . filter (== 'o') $ s


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

main = do
  [a, b, c, x, y] <- map (read::String -> Int) . words <$> getLine
  let (d, e, z, w) = if x < y then (b, a, y, x) else (a, b, x, y)
    in print $ if d + e <= 2 * c
      then d * z + e * w
      else if d <= 2 * c
        then 2 * c * w + d * (z - w)
        else 2 * c * z

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


main = do
 [a,b,c,x,y] <- map read . words <$> getLine
 let
  buyc   = if a+b<2*c then 0 else min x y * 2
  buycc  = buyc + if a<2*c   then 0 else 2*x-buyc
  buyccc = buycc + if b<2*c   then 0 else 2*y-buycc
  buya   = max (x-buyccc`div`2) 0
  buyb   = max (y-buyccc`div`2) 0
 print $ buya*a+buyb*b+buyccc*c


import Control.Applicative
import Control.Monad
--import qualified Data.Sequence as Seq
import Data.List

main = do
  [n,c] <- map read . words <$> getLine :: IO [Int]
  xvs <- replicateM n $ readIntPair . words <$> getLine
  print $ solve n c xvs --sortedBy fst

readIntPair :: [String] -> (Integer,Integer)
readIntPair =  \[a,b]->(read a,read b)

solve :: Int -> Int -> [(Integer,Integer)]-> Integer
solve n c xvs =
  maximum candidate
  where
    n' = fromIntegral n
    c' = fromIntegral c
    xvs_rev = reverse xvs
    xcs_r = scanl (\x y-> (fst y,snd x + snd y)) (0,0) xvs
    xcs_l = scanl (\x y-> (c' - fst y,snd x + snd y)) (0,0) xvs_rev
    choose m =
      let (xr,getcalr) = xcs_r!!m in
      let (xl,getcall) = maximumBy (\a b -> compare (snd a - fst a) (snd b -fst b))
            $ map ((!!) xcs_l) [0..n'-m] in
      getcalr + getcall - ((min xr xl)*2 + (max xr xl))
    candidate = map choose [0..(div n' 2+(n'`mod`2))]

Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.


solver::(Int,Int,Int)->(Int,Int)->Int
solver (a,b,c) (x,y) = if (a+b) <= 2*c
                      then (a*x) + (b*y)
                      else if (x > y) && (a > 2*c) then 2*c*x
                      else if (x < y) && (b > 2*c) then 2*c*y
                      else (min x y)*(2*c) + (if x > y then (x-y)*a else (y-x)*b  )

main::IO()
main=do
  d<-getLine
  let a:b:c:x:y:[]=map read (words d)
  print (solver (a,b,c) (x,y))


main::IO ()
main = do
    [a,b,x] <- map read . words <$> getLine
    putStrLn $ if (a+b) >= x && a < x then "YES" else "NO"

Score : 100 points

Problem Statement

There are a total of A + B cats and dogs.
Among them, A are known to be cats, but the remaining B are not known to be either cats or dogs.

Determine if it is possible that there are exactly X cats among these A + B animals.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

1 \leq X \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B X

Output

If it is possible that there are exactly X cats, print YES; if it is impossible, print NO.

Sample Input 1

3 5 4

Sample Output 1

YES

If there are one cat and four dogs among the B = 5 animals, there are X = 4 cats in total.

Sample Input 2

2 2 6

Sample Output 2

NO

Even if all of the B = 2 animals are cats, there are less than X = 6 cats in total.

Sample Input 3

5 3 2

Sample Output 3

NO

Even if all of the B = 3 animals are dogs, there are more than X = 2 cats in total.


module Main where

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
    [a, b, x] <- fmap read . words <$> getLine
    if a <= x && x <= a + b
        then putStrLn "YES"
        else putStrLn "NO"


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
import qualified Data.ByteString.Char8 as BC
import           Data.Maybe            (fromJust)

main :: IO ()
main = do
  [a, b, x] <- getInts
  putStrLn $ if a <= x && x <= a + b then "YES" else "NO"

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

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


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

main :: IO()
main = do
  [n, m, x] <- map read . words <$> getLine
  a <- map read . words <$> getLine
  printf "%s" $ slv n m x a

slv :: Int -> Int -> Int -> [Int] -> String
slv n m x a | slen > tlen = show tlen
            | otherwise = show slen
  where (s, t) = span (< m) a
        slen = length s
        tlen = length t

Score : 200 points

Problem Statement

There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right.

Initially, you are in Square X.
You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N.
However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1.
It is guaranteed that there is no toll gate in Square 0, Square X and Square N.

Find the minimum cost incurred before reaching the goal.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

1 \leq X \leq N - 1

1 \leq A_1 < A_2 < ... < A_M \leq N

A_i \neq X

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M X
A_1 A_2 ... A_M

Output

Print the minimum cost incurred before reaching the goal.

Sample Input 1

5 3 3
1 2 4

Sample Output 1

1

The optimal solution is as follows:

First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.

Then, travel from Square 4 to Square 5. This time, no cost is incurred.

Now, we are in Square 5 and we have reached the goal.

In this case, the total cost incurred is 1.

Sample Input 2

7 3 2
4 5 6

Sample Output 2

0

We may be able to reach the goal at no cost.

Sample Input 3

10 7 5
1 2 3 4 6 8 9

Sample Output 3

3


import Control.Arrow
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as B
import Data.Ord

main :: IO ()
main = getLine >> readLine >>= printRes . solve
    where
        printRes = putStrLn . unwords . map show

-- |
-- >>> solve [6, 9, 4, 2, 11]
-- [11,6]
-- >>> solve [100, 0]
-- [100,0]
solve :: [Int] -> [Int]
solve = check . sortBy (flip compare)
    where
        check (x : xs) = [x, head $ sortBy cmpf xs]
            where
                hx = x `div` 2
                cmpf = comparing (abs . (hx -))

readLine :: IO [Int]
readLine = unfoldr (\s -> second (maybe B.empty snd . B.uncons) <$> B.readInt s) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine

Score : 400 points

Problem Statement

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


import Data.List
main = do
  x <- length . group . sort <$> getLine
  putStrLn $ if x==3 then "Yes" else "No"

Score : 100 points

Problem Statement

You are given a string S of length 3 consisting of a, b and c. Determine if S can be obtained by permuting abc.

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If S can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


import Data.List (sort)

main = interact $ \ s ->
  if "abc" == sort s then "Yes" else "No"


import Data.List

main = do
  [a,b,k] <- map read . words <$> getLine :: IO [Int]
  putStr $ unlines . map show . map head . group . sort $ [x | x <- [a..a+k-1], b >= x] ++ [x | x <- [b-k+1..b], a <= x]

Score : 200 points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.

Constraints

1 \leq A \leq B \leq 10^9

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

3 is the first smallest integer among the integers between 3 and 8.

4 is the second smallest integer among the integers between 3 and 8.

7 is the second largest integer among the integers between 3 and 8.

8 is the first largest integer among the integers between 3 and 8.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


import Data.List

main = do
   [a,b,k] <- map read . words <$> getLine
   mapM_ print $ nub (take k [a..b] ++ drop (b - a + 1 - k) [a..b])


import Control.Applicative
import Data.List

check :: [Integer] -> [Integer]
check [a, b, k]
    | b - a <= 2 * k = [a..b]
    | otherwise = [a..(a + k - 1)] ++ [(b - k + 1)..(b)]

print_all :: [Integer] -> IO ()
print_all [] = return () :: IO ()
print_all (f:rest) = do
    print f
    print_all rest

main = do
    a <- check <$> map (\a -> read a :: Integer) <$> words <$> getLine
    print_all a


solve a b k =
  take k l ++ drop (len - k) l
  where
    l = [a..b]
    len = length l

main = do
  [a,b,k] <- map read . words <$> getLine :: IO [Int]
  mapM print (solve a b k)


import Control.Applicative
import Data.List

main = do
    nums@[a,b,c] <- sort.map read.words <$> getLine :: IO [Int]
    if c == a && c == b then putStrLn "0" else putStrLn.show $ count 0 [a,b,c]

count n [a,b,x] = if a' == x && b' == x then (n+1) else count (n+1) nums where
    nums = sort [x,a',b']
    x' = foldl max 0 [x,a',b']
    (a',b') = if (x >= a+2) then (a+2,b) else  (a+1,b+1)

Score : 300 points

Problem Statement

You are given three integers A, B and C. Find the minimum number of operations required to make A, B and C all equal by repeatedly performing the following two kinds of operations in any order:

Choose two among A, B and C, then increase both by 1.

Choose one among A, B and C, then increase it by 2.

It can be proved that we can always make A, B and C all equal by repeatedly performing these operations.

Constraints

0 \leq A,B,C \leq 50

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the minimum number of operations required to make A, B and C all equal.

Sample Input 1

2 5 4

Sample Output 1

2

We can make A, B and C all equal by the following operations:

Increase A and C by 1. Now, A, B, C are 3, 5, 5, respectively.

Increase A by 2. Now, A, B, C are 5, 5, 5, respectively.

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23


import Data.List
import qualified Data.Set as S

main = do
    s<-getLine::IO String
    let cs = foldl (flip S.delete) (S.fromList ['a'..'z']) s
    putStrLn $ if not $ null cs then s ++ [S.findMin cs] else sol cs $ reverse s
--
sol _ [_] = "-1"
sol cs (c:a:s)
    | a < cm = reverse $ cm:s
    | otherwise = sol cs' (a:s)
    where
        cs' = S.insert c cs
        cm = S.findMin cs'

Score : 300 points

Problem Statement

Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.

A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, atcoder, zscoder and agc are diverse words while gotou and connect aren't diverse words.

Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 \leq |S| \leq 26

S is a diverse word.

Input

Input is given from Standard Input in the following format:

S

Output

Print the next word that appears after S in the dictionary, or -1 if it doesn't exist.

Sample Input 1

atcoder

Sample Output 1

atcoderb

atcoderb is the lexicographically smallest diverse word that is lexicographically larger than atcoder. Note that atcoderb is lexicographically smaller than b.

Sample Input 2

abc

Sample Output 2

abcd

Sample Input 3

zyxwvutsrqponmlkjihgfedcba

Sample Output 3

-1

This is the lexicographically largest diverse word, so the answer is -1.

Sample Input 4

abcdefghijklmnopqrstuvwzyx

Sample Output 4

abcdefghijklmnopqrstuvx


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

Score : 100 points

Problem Statement

An elementary school student Takahashi has come to a variety store.

He has two coins, A-yen and B-yen coins (yen is the currency of Japan), and wants to buy a toy that costs C yen. Can he buy it?

Note that he lives in Takahashi Kingdom, and may have coins that do not exist in Japan.

Constraints

All input values are integers.

1 \leq A, B \leq 500

1 \leq C \leq 1000

Input

Input is given from Standard Input in the following format:

A B C

Output

If Takahashi can buy the toy, print Yes; if he cannot, print No.

Sample Input 1

50 100 120

Sample Output 1

Yes

He has 50 + 100 = 150 yen, so he can buy the 120-yen toy.

Sample Input 2

500 100 1000

Sample Output 2

No

He has 500 + 100 = 600 yen, but he cannot buy the 1000-yen toy.

Sample Input 3

19 123 143

Sample Output 3

No

There are 19-yen and 123-yen coins in Takahashi Kingdom, which are rather hard to use.

Sample Input 4

19 123 142

Sample Output 4

Yes


module Main where

import qualified Data.Map as Map
import Control.Monad

main :: IO ()
main = do
    n <- read <$> getLine
    s <- replicateM n getLine
    m <- read <$> getLine
    t <- replicateM m getLine
    print $ solve s t

solve :: [String] -> [String] -> Int
solve s t =
    let l = ((\x -> (x, 1)) <$> s) ++ ((\x -> (x, -1)) <$> t)
        m = Map.fromListWith (+) l
    in  Map.foldr (+) 0 $ Map.filter (>0) m


module Main where

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

main :: IO ()
main = do
    n  <- read <$> getLine
    rs <- replicateM n $ do
        [x, y] <- map read . words <$> getLine
        return (x, y)
    bs <- replicateM n $ do
        [x, y] <- map read . words <$> getLine
        return (x, y)
    print $ solve (sortBy (flip compare) rs) bs

solve :: [(Int, Int)] -> [(Int, Int)] -> Int
solve [] _ = 0
solve rs bs =
    let (x, y) : rs' = rs
        bCand        = filter (\(a, b) -> x < a && y < b) bs
        compSnd p q = snd p `compare` snd q
    in  if null bCand
            then solve rs' bs
            else (1 +) $ solve rs' $ delete (minimumBy compSnd bCand) bs

Score : 400 points

Problem Statement

On a two-dimensional plane, there are N red points and N blue points.
The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).

A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, and the y-coordinate of the red point is also smaller than that of the blue point.

At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.

Constraints

All input values are integers.

1 \leq N \leq 100

0 \leq a_i, b_i, c_i, d_i < 2N

a_1, a_2, ..., a_N, c_1, c_2, ..., c_N are all different.

b_1, b_2, ..., b_N, d_1, d_2, ..., d_N are all different.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N

Output

Print the maximum number of friendly pairs.

Sample Input 1

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

Sample Output 1

2

For example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).

Sample Input 2

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

Sample Output 2

2

For example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).

Sample Input 3

2
2 2
3 3
0 0
1 1

Sample Output 3

0

It is possible that no pair can be formed.

Sample Input 4

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

Sample Output 4

5

Sample Input 5

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

Sample Output 5

4


import Control.Monad
import Data.List

solve [] _ acc = acc
solve ((a,b):abs) cds acc =
  case filter (\y-> compare a (fst y) == LT && compare b (snd y) == LT ) cds of
    [] -> solve abs cds acc
    xs -> solve abs cds (1+acc)
    --(delete (snd $ minimum $ map (\(x,y) -> ((x-a)^2+(y-b)^2,(x,y))) xs) cds) (acc+1)

readInt = read :: String -> Int

main = do
  n <- read <$> getLine
  abs <- replicateM n $ (\[a,b] -> (readInt a,readInt b)) . words <$> getLine
  cds <- replicateM n $ (\[a,b] -> (readInt a,readInt b)) . words <$> getLine
  print $ solve abs cds 0


import Control.Monad

main::IO ()
main = do
    [a,b,c] <- replicateM 3 getLine
    putStrLn $ [a !! 0] ++ [b !! 1] ++ [c !! 2]

Score : 100 points

Problem Statement

We have a 3×3 square grid, where each square contains a lowercase English letters.
The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.

Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Constraints

Input consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

c_{11}c_{12}c_{13}
c_{21}c_{22}c_{23}
c_{31}c_{32}c_{33}

Output

Print the string of length 3 that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Sample Input 1

ant
obe
rec

Sample Output 1

abc

The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.

Sample Input 2

edu
cat
ion

Sample Output 2

ean


module Main where

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

main :: IO ()
main = do
    [a, _, _] <- getLine
    [_, b, _] <- getLine
    [_, _, c] <- getLine
    putStrLn [a, b, c]


main = do
   (a:_) <- getLine
   (_:b:_) <- getLine
   [_,_,c] <- getLine
   putStrLn [a,b,c]


main = print . (\[n,m] -> (n-2)*(m-2)) . map read . words =<< getLine

Score : 300 points

Problem Statement

There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region.
The front and back sides of these cards can be distinguished, and initially every card faces up.

We will perform the following operation once for each square contains a card:

For each of the following nine squares, flip the card in it if it exists: the target square itself and the eight squares that shares a corner or a side with the target square.

It can be proved that, whether each card faces up or down after all the operations does not depend on the order the operations are performed.
Find the number of cards that face down after all the operations.

Constraints

1 \leq N,M \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of cards that face down after all the operations.

Sample Input 1

2 2

Sample Output 1

0

We will flip every card in any of the four operations. Thus, after all the operations, all cards face up.

Sample Input 2

1 7

Sample Output 2

5

After all the operations, all cards except at both ends face down.

Sample Input 3

314 1592

Sample Output 3

496080


main :: IO ()
main = do
    input <- words <$> getLine
    print $ abs (read (head input)-2) * abs (read (input!!1)-2)


import           Control.Applicative
import           Control.DeepSeq
import           Control.Monad
import           Control.Monad.ST
import qualified Data.Array                    as A
import qualified Data.Array.IArray             as IA
import qualified Data.Array.IO                 as AI
import qualified Data.Array.MArray             as MA
import qualified Data.Array.ST                 as STA
import qualified Data.Array.Unboxed            as AU
import           Data.Bits
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import qualified Data.Graph                    as G
import           Data.Int
import qualified Data.IntMap                   as IM
import qualified Data.IntSet                   as IS
import           Data.List
import qualified Data.Map.Strict               as M
import           Data.Maybe
import           Data.Ord
import qualified Data.Sequence                 as SQ
import qualified Data.Set                      as S
import           Data.Time
import qualified Data.Tree                     as T
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM

readInt :: IO Int
readInt = fst . fromJust . BS.readInt <$> BS.getLine

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

readIntLists :: Int -> IO [[Int]]
readIntLists n = replicateM n readInts

readInteger :: IO Integer
readInteger = fst . fromJust . BS.readInteger <$> BS.getLine

readIntegers :: IO [Integer]
readIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

readIntegerLists :: Int -> IO [[Integer]]
readIntegerLists n = replicateM n readIntegers

readStrings :: IO [String]
readStrings = map BS.unpack . BS.words <$> BS.getLine

readStringLists :: Int -> IO [[String]]
readStringLists n = replicateM n <$> readStrings

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

count :: Eq a => a -> [a] -> Int
count a as = length $ filter (== a) as

put :: Show a => a -> IO ()
put = putStr . show

putList :: Show a => [a] -> IO ()
putList [n     ] = put n
putList (n : ns) = do
  put n
  putStr " "
  putList ns

putStrList :: [String] -> IO ()
putStrList [n     ] = putStr n
putStrList (n : ns) = do
  putStr n
  putStr " "
  putStrList ns

yesNoUpper b | b         = putStrLn "YES"
             | otherwise = putStrLn "NO"

yesNo b | b         = putStrLn "Yes"
        | otherwise = putStrLn "No"

divCeiling x n | b == 0    = a
               | otherwise = a + 1
  where (a, b) = x `divMod` n

main = do
  [n, k] <- readInts
  print $ solve n k

solve n k = (sum $ map (\b -> f b k n) bs )- m
 where
  bs = [k + 1 .. n]
  m | k /= 0    = 0
    | otherwise = k

f b k n = p * max 0 (b - k) + max 0 (r - k + 1)
 where
  ms     = [k .. b - 1]
  (p, r) = n `divMod` b
  m | r == 0    = b + 1
    | otherwise = 0

g b k n m | m /= 0    = (n - m) `div` b + 1
          | otherwise = (n - m) `div` b

Score : 400 points

Problem Statement

Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten.
He remembers that the remainder of a divided by b was greater than or equal to K.
Find the number of possible pairs that he may have had.

Constraints

1 \leq N \leq 10^5

0 \leq K \leq N-1

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of possible pairs that he may have had.

Sample Input 1

5 2

Sample Output 1

7

There are seven possible pairs: (2,3),(5,3),(2,4),(3,4),(2,5),(3,5) and (4,5).

Sample Input 2

10 0

Sample Output 2

100

Sample Input 3

31415 9265

Sample Output 3

287927211


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

main :: IO ()
main = do
    -- 整数の入力
    a <- readLn
    -- 出力
    putStrLn $ show $ a `div` 3

Score : 100 points

Problem Statement

There are N students in a school.

We will divide these students into some groups, and in each group they will discuss some themes.

You think that groups consisting of two or less students cannot have an effective discussion, so you want to have as many groups consisting of three or more students as possible.

Divide the students so that the number of groups consisting of three or more students is maximized.

Constraints

1 \leq N \leq 1000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N

Output

If you can form at most x groups consisting of three or more students, print x.

Sample Input 1

8

Sample Output 1

2

For example, you can form a group of three students and another of five students.

Sample Input 2

2

Sample Output 2

0

Sometimes you cannot form any group consisting of three or more students, regardless of how you divide the students.

Sample Input 3

9

Sample Output 3

3


import Data.List

gather [] = []
gather list@(x:xs) = length b : gather a
  where
    (b,a) = span (==x) list

main = do
  n <- getLine
  s <- getContents >>= return . gather . sort . map head . (filter (\(x:_) -> elem x "MARCH")) . lines

  print $ f s

  where
    f [] = 0
    f (x:xs) = x * (g xs) + f xs
    g [] = 0
    g (x:xs) = x * (sum xs) + g xs

Score : 300 points

Problem Statement

There are N people. The name of the i-th person is S_i.

We would like to choose three people so that the following conditions are met:

The name of every chosen person begins with M, A, R, C or H.

There are no multiple people whose names begin with the same letter.

How many such ways are there to choose three people, disregarding order?

Note that the answer may not fit into a 32-bit integer type.

Constraints

1 \leq N \leq 10^5

S_i consists of uppercase English letters.

1 \leq |S_i| \leq 10

S_i \neq S_j (i \neq j)

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If there are x ways to choose three people so that the given conditions are met, print x.

Sample Input 1

5
MASHIKE
RUMOI
OBIRA
HABORO
HOROKANAI

Sample Output 1

2

We can choose three people with the following names:

MASHIKE, RUMOI, HABORO

MASHIKE, RUMOI, HOROKANAI

Thus, we have two ways.

Sample Input 2

4
ZZ
ZZZ
Z
ZZZZZZZZZZ

Sample Output 2

0

Note that there may be no ways to choose three people so that the given conditions are met.

Sample Input 3

5
CHOKUDAI
RNG
MAKOTO
AOKI
RINGO

Sample Output 3

7


import qualified Data.Map.Strict as M
import Data.List
import Control.Monad

count :: [Char] -> M.Map Char Int
count = foldl' step $ M.fromList [(ini, 0) | ini <- "MARCH"]
  where step tbl ch
          | ch `elem` "MARCH" = M.adjust (1+) ch tbl
          | otherwise = tbl

choices :: [[Char]]
choices = nub $ map (sort . take 3) $ permutations "MARCH"

patterns :: M.Map Char Int -> Int
patterns tbl = sum [ product $ map (tbl M.!) l
                   | l <- choices ]

main :: IO ()
main = do
  n <- readLn
  ss <- replicateM n getLine
  let table = count $ map head ss
  print $ patterns table


import Data.List
{-

-}
main = do
    n <- getLine >>= return . read
    strlist <- sequence . take n $ repeat getLine
    let initials = map (\xs -> (head xs) : "") strlist
    let ans = solve initials
    print ans

solve :: [String] -> Integer
solve initials = m*a*r + m*a*c + m*a*h + m*r*c + m*r*h + m*c*h + a*r*c + a*r*h + a*c*h + r*c*h
    where m = count "M" initials
          a = count "A" initials
          r = count "R" initials
          c = count "C" initials
          h = count "H" initials

count :: String -> [String] -> Integer
count search list = toInteger . length $ [e | e <- list, e == search]


import Data.Char
main=getLine>>=print.f
f (a:r)
 |all(=='9')r=x
 |otherwise=x-1
 where x=digitToInt a+9*length r

Score : 300 points

Problem Statement

Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Constraints

1\leq N \leq 10^{16}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Sample Input 1

100

Sample Output 1

18

For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.

Sample Input 2

9995

Sample Output 2

35

For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.

Sample Input 3

3141592653589793

Sample Output 3

137


import           Data.Char

main :: IO ()
main = do
    n <- map digitToInt <$> getLine
    print $ solve n

solve :: [Int] -> Int
solve (x:xs)
    | all (== 9) xs = x + 9 * length xs
    | otherwise = x + 9 * length xs - 1


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict          as IM
import qualified Data.IntSet                 as IS
import           Data.List
import qualified Data.Map.Strict             as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive.MutVar
import qualified Data.Set                    as S
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Debug.Trace
import           Foreign                     hiding (void)
import           Unsafe.Coerce

main :: IO ()
main = do
    !n <- readLn :: IO Int
    points <- map(\(x,y)->P (fromIntegral x) (fromIntegral y)).U.toList.U.unfoldrN n parseInt2 <$> B.getContents
    mapM_ print $ solve n points

solve :: Int -> [Point] -> [Double]
solve 2 _      = [0.5, 0.5]
solve n points = [maybe 0.0 id $ M.lookup p probs|p<-points]
    where
      convex = convexHull points
      doubleDot x y = fromIntegral $ dot x y
      probs :: M.Map Point Double
      probs = case convex of
          [x, y] -> M.fromList [(x,0.5),(y,0.5)]
          _      -> go M.empty $ convex ++ convex
      go :: M.Map Point Double -> [Point] -> M.Map Point Double
      go res (x:o:y:rest) = go (M.insert o (acos c / pi / 2) res) (o:y:rest)
        where
          c = -doubleDot(x-o)(y-o) / (sqrt(doubleDot(x-o)(x-o)) * sqrt(doubleDot(y-o)(y-o)))
      go res _ = res
        where
          ps = map snd $ M.toList res

-------------------------------------------------------------------------------
type Parser a = B.ByteString -> Maybe (a, B.ByteString)

parseInt :: Parser Int
parseInt = B.readInt . B.dropWhile isSpace

parseInt2 :: Parser (Int, Int)
parseInt2 = runStateT $
    (,) <$> StateT (B.readInt . B.dropWhile isSpace)
    <*> StateT (B.readInt . B.unsafeTail)

data Point = P !Integer !Integer deriving (Eq, Ord)
type Seg = (Point, Point)
type Polygon = [Point]
type Convex = [Point]

instance Show Point where
  show (P x y) = show (x,y)

instance Num Point where
  (P x0 y0) + (P x1 y1) = P (x0 + x1) (y0 + y1)
  (P x0 y0) - (P x1 y1) = P (x0 - x1) (y0 - y1)
  (P x0 y0) * (P x1 y1) = P (x0 * x1 - y0 * y1) (x0 * y1 + x1 * y0)
  negate (P x y) = P (negate x) (negate y)
  abs _ = undefined
  signum _ = undefined
  fromInteger n = P n 0

infixr 7 *:
(*:) :: Integer -> Point -> Point
(*:) !k (P x y) = P (k * x) (k * y)
{-# INLINE (*:) #-}

dot :: Point -> Point -> Integer
dot (P x0 y0) (P x1 y1) = x0 * x1 + y0 * y1
{-# INLINE dot #-}

cross :: Point -> Point -> Integer
cross (P x0 y0) (P x1 y1) = x0 * y1 - y0 * x1
{-# INLINE cross #-}

--        v
--       /  <==> area o u v > 0
--  o---u
area :: Point -> Point -> Point -> Integer
area o u v = (u - o) `cross` (v - o)
{-# INLINE area #-}

--        v
--       /  <==> compCCW o u v == LT
--  o---u
compCCW :: Point -> Point -> Point -> Ordering
compCCW o u v = compare 0 $ area o u v
{-# INLINE compCCW #-}

compCW :: Point -> Point -> Point -> Ordering
compCW o u v = compCCW o v u
{-# INLINE compCW #-}

onSeg :: Point -> Seg -> Bool
onSeg p (q0, q1) = (q0 - p) `cross` (q1 - p) == 0
                 && (q0 - p) `dot` (q1 - p) < 0
{-# INLINE onSeg #-}

segIntersect :: Seg -> Seg -> Bool
segIntersect (p0, p1) (q0, q1) = (area p0 q0 q1) * (area p1 q0 q1) < 0
                               && (area q0 p0 p1) * (area q1 p0 p1) < 0
{-# INLINE segIntersect #-}

convexHull :: [Point] -> Convex
convexHull ps = reverse.go [v0].sortBy (compCCW v0) $ filter (/=v0) ps
   where
     !v0 = minimum ps
     go (p:q:conv) (r:rs) = case compCCW q p r of
        LT -> go (r:p:q:conv) rs
        GT -> go (q:conv) (r:rs)
        EQ | (q-p) `dot` (r-p) < 0 -> go (r:q:conv) rs -- q--p--r
           | otherwise             -> go (p:q:conv) rs -- q--r--p
     go [p] (r:rs) = go [r,p] rs
     go conv [] = conv

Score : 600 points

Problem Statement

There are N holes in a two-dimensional plane. The coordinates of the i-th hole are (x_i,y_i).

Let R=10^{10^{10^{10}}}. Ringo performs the following operation:

Randomly choose a point from the interior of a circle of radius R centered at the origin, and put Snuke there. Snuke will move to the hole with the smallest Euclidean distance from the point, and fall into that hole. If there are multiple such holes, the hole with the smallest index will be chosen.

For every i (1 \leq i \leq N), find the probability that Snuke falls into the i-th hole.

Here, the operation of randomly choosing a point from the interior of a circle of radius R is defined as follows:

Pick two real numbers x and y independently according to uniform distribution on [-R,R].

If x^2+y^2\leq R^2, the point (x,y) is chosen. Otherwise, repeat picking the real numbers x,y until the condition is met.

Constraints

2 \leq N \leq 100

|x_i|,|y_i| \leq 10^6(1\leq i\leq N)

All given points are pairwise distinct.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print N real numbers. The i-th real number must represent the probability that Snuke falls into the i-th hole.

The output will be judged correct when, for all output values, the absolute or relative error is at most 10^{-5}.

Sample Input 1

2
0 0
1 1

Sample Output 1

0.5
0.5

If Ringo put Snuke in the region x+y\leq 1, Snuke will fall into the first hole. The probability of this happening is very close to 0.5.
Otherwise, Snuke will fall into the second hole, the probability of which happening is also very close to 0.5.

Sample Input 2

5
0 0
2 8
4 5
2 6
3 10

Sample Output 2

0.43160120892732328768
0.03480224363653196956
0.13880483535586193855
0.00000000000000000000
0.39479171208028279727


main :: IO()
main = do
    n <- readLn
    a <- readLn
    putStrLn $ if (mod n 500) <= a then "Yes" else "No"

Score: 100 points

Problem Statement

E869120 has A 1-yen coins and infinitely many 500-yen coins.

Determine if he can pay exactly N yen using only these coins.

Constraints

N is an integer between 1 and 10000 (inclusive).

A is an integer between 0 and 1000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
A

Output

If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print Yes; otherwise, print No.

Sample Input 1

2018
218

Sample Output 1

Yes

We can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer is Yes.

Sample Input 2

2763
0

Sample Output 2

No

When we have no 1-yen coins, we can only pay a multiple of 500 yen using only 500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.

Sample Input 3

37
514

Sample Output 3

Yes


f :: Int -> Int -> String
f n a
  | n `mod` 500 <= a = "Yes"
  | otherwise = "No"

main :: IO()
main = do
  d <- getLine
  let n = read d :: Int
  b <- getLine
  let a = read b :: Int
  print(f n a)


import Data.List

main = do
       n<-getLine
       a<-getLine
       let n1=read n::Int
           a1=read a::Int
       putStrLn $ if (n1 `mod` 500) <= a1 then "Yes" else "No"


main::IO()
main=do
  nc<-getLine
  ac<-getLine
  let (n,a)=(read nc,read ac)
  putStr (if mod n 500 <= (a::Int) then "Yes\n" else "No\n"  )


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

--------------------------------------------------------------------------
solve xss = cond1 && cond2
    where
        [as,bs,cs] = map sum xss
        [xs,ys,zs] = map sum $ transpose xss
        cond1 = ((abs $ as - bs) `mod` 3 == 0) && ((abs $ bs - cs) `mod` 3 == 0) && ((abs $ cs - as) `mod` 3 == 0)
        cond2 = ((abs $ xs - ys) `mod` 3 == 0) && ((abs $ ys - zs) `mod` 3 == 0) && ((abs $ zs - xs) `mod` 3 == 0)

main = do
    xss <- replicateM 3 sLineToIntL
    yesnoL $ solve xss
--------------------------------------------------------------------------

-- 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: 300 points

Problem Statement

We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is equal to a_i + b_j.

Determine if he is correct.

Constraints

c_{i, j} \ (1 \leq i \leq 3, 1 \leq j \leq 3) is an integer between 0 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

c_{1,1} c_{1,2} c_{1,3}
c_{2,1} c_{2,2} c_{2,3}
c_{3,1} c_{3,2} c_{3,3}

Output

If Takahashi's statement is correct, print Yes; otherwise, print No.

Sample Input 1

1 0 1
2 1 2
1 0 1

Sample Output 1

Yes

Takahashi is correct, since there are possible sets of integers such as: a_1=0,a_2=1,a_3=0,b_1=1,b_2=0,b_3=1.

Sample Input 2

2 2 2
2 1 2
2 2 2

Sample Output 2

No

Takahashi is incorrect in this case.

Sample Input 3

0 8 8
0 8 8
0 8 8

Sample Output 3

Yes

Sample Input 4

1 8 6
2 9 7
0 7 7

Sample Output 4

No


import Data.Char
import Data.List
import qualified Data.ByteString.Char8 as B
main=B.interact$B.pack.f.unfoldr(B.readInt.B.dropWhile isSpace)
f (n:abs) =if s1 <= st && s2 <= st then "Yes" else "No"
    where
        (as,bs) = splitAt n abs
        s1 = sum(map sol1$zip as bs)
        s2 = sum(map sol2$zip as bs)
        st = sum bs - sum as
sol1 (a,b)
    | a<b = (b-a+1)`div`2
    | otherwise = 0
sol2 (a,b)
    | a>b = a-b
    | otherwise = 0

Score : 300 points

Problem Statement

You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N.
Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal.

Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two actions simultaneously:

Add 2 to a_i.

Add 1 to b_j.

Constraints

1 ≤ N ≤ 10 000

0 ≤ a_i,b_i ≤ 10^9 (1 ≤ i ≤ N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 .. a_N
b_1 b_2 .. b_N

Output

If we can repeat the operation zero or more times so that the sequences a and b become equal, print Yes; otherwise, print No.

Sample Input 1

3
1 2 3
5 2 2

Sample Output 1

Yes

For example, we can perform three operations as follows to do our job:

First operation: i=1 and j=2. Now we have a = \{3,2,3\}, b = \{5,3,2\}.

Second operation: i=1 and j=2. Now we have a = \{5,2,3\}, b = \{5,4,2\}.

Third operation: i=2 and j=3. Now we have a = \{5,4,3\}, b = \{5,4,3\}.

Sample Input 2

5
3 1 4 1 5
2 7 1 8 2

Sample Output 2

No

Sample Input 3

5
2 7 1 8 2
3 1 4 1 5

Sample Output 3

No


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 Arr = IOUArray Int Int
type ArrB = IOUArray Int Bool
type Edge = (Int, Int)

main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  a <- getIntListBC
  edge <- if m > 0
            then getInt2DListBC
            else return [] :: IO [[Int]]
  parent <- newListArray (-1, n-1) [-1..n-1] :: IO Arr
  writeArray parent (-1) 0
  mark <- newArray (0, n-1) False :: IO ArrB
  let weight = sort $ zip a [0..n-1]
  unionFind parent edge
  mapM (getRepresentative parent) [0..n-1]
  l <- length . nub . tail <$> getElems parent
  weight' <- select parent mark l weight
  single <- subtract 1 . length . filter (==1) . map length . group . sort <$> getElems parent
  ans1 <- if l > 1 then readArray parent (-1) else return 0
  let ans2 = sum . map fst . take (l-2) $ weight'
  print ans1
  print ans2
  if single > (n - single) - (l - single - 1)*2
    then putStrLn "Impossible"
    else print $ ans1 + ans2

solve :: Arr -> Arr -> Int -> [(Int, Int)] -> IO Int
solve _ _ _ [] = return 0
solve _ _ 0 _ = return 0
solve parent children i ((w, v):s) = do
  p <- readArray parent v
  c <- readArray children p
  if c > 0
    then do
      dec children p
      ans <- solve parent children (i-1) s
      return $ w + ans
    else do
      solve parent children i s

select :: Arr -> ArrB -> Int -> [(Int, Int)] -> IO [(Int, Int)]
select _      _    _ []          = return []
select _      _    0 s           = return s
select parent mark n ((w, v):ws) = do
  p <- readArray parent v
  used <- readArray mark p
  if used || n <= 0
    then do
      l <- select parent mark n ws
      return $ (w, v):l
    else do
      writeArray mark p True
      s <- readArray parent (-1)
      writeArray parent (-1) $ s + w
      select parent mark (n-1) ws

count :: Arr -> Arr -> [Int] -> IO ()
count _ _ [] = return ()
count parent children (v:vs) = do
  p <- getRepresentative parent v
  inc children p
  count parent children vs

inc :: Arr -> Int -> IO ()
inc arr i = do
  x <- readArray arr i
  writeArray arr i $ x + 1

dec :: Arr -> Int -> IO ()
dec arr i = do
  x <- readArray arr i
  writeArray arr i $ x - 1

unionFind :: Arr -> [[Int]] -> IO Arr
unionFind memo [] = return memo
unionFind memo ([i, j]:es) = do
  pI <- getRepresentative memo i
  pJ <- getRepresentative memo j
  if pI == pJ then unionFind memo es
              else do
                writeArray memo pI pJ
                unionFind memo es

getRepresentative :: Arr -> Int -> IO Int
getRepresentative memo i = do
  parent <- readArray memo i
  if i == parent
    then return i
    else do
      pp <- getRepresentative memo parent
      writeArray memo i pp
      return pp

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

Score : 600 points

Problem Statement

You are given a forest with N vertices and M edges. The vertices are numbered 0 through N-1.
The edges are given in the format (x_i,y_i), which means that Vertex x_i and y_i are connected by an edge.

Each vertex i has a value a_i.
You want to add edges in the given forest so that the forest becomes connected.
To add an edge, you choose two different vertices i and j, then span an edge between i and j.
This operation costs a_i + a_j dollars, and afterward neither Vertex i nor j can be selected again.

Find the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Constraints

1 ≤ N ≤ 100,000

0 ≤ M ≤ N-1

1 ≤ a_i ≤ 10^9

0 ≤ x_i,y_i ≤ N-1

The given graph is a forest.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_0 a_1 .. a_{N-1}
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the minimum total cost required to make the forest connected, or print Impossible if it is impossible.

Sample Input 1

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

Sample Output 1

7

If we connect vertices 0 and 5, the graph becomes connected, for the cost of 1 + 6 = 7 dollars.

Sample Input 2

5 0
3 1 4 1 5

Sample Output 2

Impossible

We can't make the graph connected.

Sample Input 3

1 0
5

Sample Output 3

0

The graph is already connected, so we do not need to add any edges.


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE TypeFamilies      #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict          as IM
import qualified Data.IntSet                 as IS
import           Data.List                   hiding (insert)
import qualified Data.Map.Strict             as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive.MutVar
import qualified Data.Set                    as S
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Debug.Trace
import           Foreign                     hiding (void)
import           GHC.Exts
import           Unsafe.Coerce

main :: IO ()
main = do
    [n, m] <- map read.words <$> getLine :: IO [Int]
    xs <- U.unfoldrN n parseInt <$> B.getLine
    es <- U.unfoldrN m parseInt2 <$> B.getContents
    putStrLn.maybe"Impossible"show $ solve n xs es

solve :: Int -> U.Vector Int -> U.Vector (Int, Int) -> Maybe Int
solve 1 _ _ = Just 0
solve 2 xs es
  | U.null es = Just $ U.sum xs
  | otherwise = Just 0
solve n xs es = go 0 (toList $ mergePairs iso) $ fromList nonIso
  where
    (iso, nonIso) = partition isSingleton $ forest n xs es
    go :: Int -> [Int] -> Heap (Heap Int) -> Maybe Int
    go !res is hh
--      | traceShow hh False = undefined
      | isSingleton hh = complete res is hh
      | Just (h', hh') <- deleteFindMin hh
      , Just (h'', hh'') <- deleteFindMin hh'
      , Just (x, rx) <- deleteFindMin h'
      , Just (y, ry) <- deleteFindMin h'' =
          case merge rx ry of
              Empty
                | isEmpty hh'', null is -> Just $ res + x + y
                | otherwise -> Nothing
              Fork z [] -> go (res + x + y) (z:is) hh''
              rh -> go (res + x + y) is $ insert rh hh''
      | otherwise = Nothing
    complete :: Int -> [Int] -> Heap (Heap Int) -> Maybe Int
    complete res is (Fork h [])
        | length is <= length vs = Just $ res + (sum $ zipWith (+) is vs)
        | otherwise = Nothing
      where
        vs = toList h
    complete res [] Empty = Just res
    complet _ _ _ = Nothing

forest :: Int -> U.Vector Int -> U.Vector (Int, Int) -> [Heap Int]
forest n xs es = runST $ do
    uf <- newUnionFind n
    U.forM_ es $ \(x, y) ->
      uniteM x y uf

    hs <- U.foldM (\m i -> do
        p <- findM i uf
        return $ IM.insertWith merge p (singleton (U.unsafeIndex xs i)) m
        ) (IM.empty :: IM.IntMap (Heap Int)) (U.generate n id)
    return . map snd $ IM.toAscList hs

isSingleton :: Ord a => Heap a -> Bool
isSingleton (Fork _ []) = True
isSingleton _ = False
-------------------------------------------------------------------------------
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n = U.forM_ $ U.generate n id
rev !n = U.forM_ $ U.iterateN n (subtract 1) (n - 1)
for :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for !s !t = U.forM_ $ U.generate (t - s) (+s)
{-# INLINE rep #-}
{-# INLINE rev #-}
{-# INLINE for #-}

type Parser a = B.ByteString -> Maybe (a, B.ByteString)

parseInt :: Parser Int
parseInt = B.readInt . B.dropWhile isSpace

parseInt2 :: Parser (Int, Int)
parseInt2 = runStateT $
    (,) <$> StateT (B.readInt . B.dropWhile isSpace)
        <*> StateT (B.readInt . B.unsafeTail)

data UnionFind m = UF
    { parent :: UM.MVector m Int
    , rank   :: UM.MVector m Int
    }

nothing :: Int
nothing = -1
{-# INLINE nothing #-}

newUnionFind :: PrimMonad m => Int -> m (UnionFind (PrimState m))
newUnionFind n = UF `liftM` UM.replicate n nothing `ap` UM.replicate n 0
{-# INLINE newUnionFind #-}

findM :: PrimMonad m => Int -> UnionFind (PrimState m) -> m Int
findM x uf@UF{..} = do
    px <- UM.unsafeRead parent x
    if px == nothing
    then return x
    else do
        ppx <- findM px uf
        UM.unsafeWrite parent x ppx
        return ppx
{-# INLINE findM #-}

uniteM :: PrimMonad m => Int -> Int -> UnionFind (PrimState m) -> m ()
uniteM x y uf@UF{..} = do
    px <- findM x uf
    py <- findM y uf
    when (px /= py) $ do
        rx <- UM.unsafeRead rank px
        ry <- UM.unsafeRead rank py
        case compare rx ry of
            LT -> UM.unsafeWrite parent px py
            GT -> UM.unsafeWrite parent py px
            EQ -> do
                UM.unsafeWrite parent px py
                UM.unsafeWrite rank py (ry + 1)
{-# INLINE uniteM #-}

equivM :: PrimMonad m => Int -> Int -> UnionFind (PrimState m) -> m Bool
equivM x y uf = (==) `liftM` findM x uf `ap` findM y uf
{-# INLINE equivM #-}

-- | O(n)
countM :: PrimMonad m => UnionFind (PrimState m) -> m Int
countM UF{..} = liftM (U.length . U.filter (==nothing)) $ U.unsafeFreeze parent
{-# INLINE countM #-}

data Heap a = Fork !a [Heap a] | Empty deriving Eq

instance Ord a => Ord (Heap a) where
    compare (Fork x _) (Fork y _) = compare x y
    compare Empty (Fork _ _) = LT
    compare (Fork _ _) Empty = GT
    compare _ _ = EQ

instance (Show a, Ord a) => Show (Heap a) where
    show h = show $ toList h

singleton :: a -> Heap a
singleton x = Fork x []
{-# INLINE singleton #-}

isEmpty :: Heap a -> Bool
isEmpty Empty = True
isEmpty _ = False
{-# INLINE isEmpty #-}

insert :: Ord a => a -> Heap a -> Heap a
insert x = merge (Fork x [])
{-# INLINE insert #-}

minElem :: Heap a -> Maybe a
minElem (Fork x _) = Just x
minElem _ = Nothing
{-# INLINE minElem #-}

deleteMin :: Ord a => Heap a -> Maybe (Heap a)
deleteMin (Fork _ hs) = Just $! mergePairs hs
deleteMin _ = Nothing
{-# INLINE deleteMin #-}

deleteFindMin :: Ord a => Heap a -> Maybe (a, Heap a)
deleteFindMin (Fork x hs) = Just (x, mergePairs hs)
deleteFindMin _ = Nothing
{-# INLINE deleteFindMin #-}

merge :: Ord a => Heap a -> Heap a -> Heap a
merge hx@(Fork x hxs) hy@(Fork y hys)
  | x <= y    = Fork x (hy:hxs)
  | otherwise = Fork y (hx:hys)
merge Empty hy = hy
merge hx _ = hx
{-# INLINE merge #-}

mergePairs :: Ord a => [Heap a] -> Heap a
mergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)
mergePairs [x]      = x
mergePairs []       = Empty
{-# INLINE mergePairs #-}

instance Ord a => IsList (Heap a) where
    type Item (Heap a) = a
    fromList xs = mergePairs $ map singleton xs
    toList (Fork x hs) = x : toList (mergePairs hs)
    toList Empty = []


module Main where

main = do
  l1 <- getLine
  let x = read l1
  l2 <- getLine
  let a = read l2
  l3 <- getLine
  let b = read l3
  print (mod (x - a) b)

Score : 100 points

Problem Statement

You went shopping to buy cakes and donuts with X yen (the currency of Japan).

First, you bought one cake for A yen at a cake shop.
Then, you bought as many donuts as possible for B yen each, at a donut shop.

How much do you have left after shopping?

Constraints

1 \leq A, B \leq 1 000

A + B \leq X \leq 10 000

X, A and B are integers.

Input

Input is given from Standard Input in the following format:

X
A
B

Output

Print the amount you have left after shopping.

Sample Input 1

1234
150
100

Sample Output 1

84

You have 1234 - 150 = 1084 yen left after buying a cake.
With this amount, you can buy 10 donuts, after which you have 84 yen left.

Sample Input 2

1000
108
108

Sample Output 2

28

Sample Input 3

579
123
456

Sample Output 3

0

Sample Input 4

7477
549
593

Sample Output 4

405


main = getContents >>= print . solve . map read . words

solve (x:a:b:_) = (x - a) `mod` b


import qualified Data.ByteString.Char8 as B
import qualified Data.Vector.Unboxed as VU
import Data.Maybe (fromJust)

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

main = do
  n <- readLn
  a1n <- getInts
  a2n <- getInts
  let a1nv = VU.fromList a1n
      a2nv = VU.fromList a2n
  print $ VU.maximum . VU.map (\x -> VU.sum (VU.take x a1nv) + VU.sum (VU.drop (x-1) a2nv)) $ VU.fromList [1..n]

Score : 300 points

Problem Statement

We have a 2 \times N grid. We will denote the square at the i-th row and j-th column (1 \leq i \leq 2, 1 \leq j \leq N) as (i, j).

You are initially in the top-left square, (1, 1).
You will travel to the bottom-right square, (2, N), by repeatedly moving right or down.

The square (i, j) contains A_{i, j} candies.
You will collect all the candies you visit during the travel.
The top-left and bottom-right squares also contain candies, and you will also collect them.

At most how many candies can you collect when you choose the best way to travel?

Constraints

1 \leq N \leq 100

1 \leq A_{i, j} \leq 100 (1 \leq i \leq 2, 1 \leq j \leq N)

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}

Output

Print the maximum number of candies that can be collected.

Sample Input 1

5
3 2 2 4 1
1 2 2 2 1

Sample Output 1

14

The number of collected candies will be maximized when you:

move right three times, then move down once, then move right once.

Sample Input 2

4
1 1 1 1
1 1 1 1

Sample Output 2

5

You will always collect the same number of candies, regardless of how you travel.

Sample Input 3

7
3 3 4 5 4 5 3
5 3 4 4 2 3 2

Sample Output 3

29

Sample Input 4

1
2
3

Sample Output 4

5


module Main where--
import Control.Monad

solve :: [[Int]] -> Int -> Int -> Int
solve a 1 1 = (a !! 1) !! 1
solve a (-1) _ = 0
solve a _ (-1) = 0
solve a i j = (a !! i) !! j + (max (solve a (i-1) j) (solve a i (j-1)))

main :: IO ()
main = do
        n <- readLn
        a <- map (map read . words) <$> replicateM 2 getLine
--         putStrLn $ show $ (a :: [[Int]])
        putStrLn $ show $ solve a 1 (n-1)


main =  do
  n <- readLn
  a1 <- (map read . words) <$> getLine
  a2 <- (map read . words) <$> getLine
  print $ maximum $ map (solve (a1, a2)) [1..n]

solve:: ([Int], [Int]) -> Int -> Int
solve x n = do
  let (x1, x2) = x
  let k = foldl (+) 0 (take n x1)
  let l = foldl (+) 0 (drop (n - 1) x2)
  k + l


{-# LANGUAGE ScopedTypeVariables, LambdaCase #-}

import qualified Data.List as List
import qualified Data.Set as Set

main :: IO ()
main = do
    [n] :: [Int] <- map read . words <$> getLine
    aue :: [Int] <- map read. words <$> getLine
    ashita :: [Int] <- map read . words <$> getLine
    print $ maximum [ sum (take k aue) + sum (drop (pred k) ashita) | k <- [1..n]]


{-# OPTIONS_GHC -O #-}
{-# LANGUAGE ViewPatterns #-}

import Control.Monad
import Control.Monad.ST
import Data.List
import Data.Maybe
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as VM
import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap as M
import qualified Data.Sequence as SQ
import Data.Sequence ((|>), (<|), ViewL(..), ViewR(..))

main = do
    (n:m:_)<-map read.words<$>getLine::IO [Int]
    lrds <- replicateM m $ unfoldr (B.readInt.B.dropWhile(==' ')) <$> B.getLine :: IO[[Int]]
    --
    let grp = foldl (\m (l:r:d:_)->M.alter (ins l (-d)) r $ M.alter (ins r d) l m) M.empty lrds
    --
--    print $ map (\(l:r:d:_)->chk n grp l r d) lrds
    putStrLn $ if all (\(l:r:d:_) -> chk n grp l r d) lrds then "Yes" else "No"
--
ins ::Int -> Int -> Maybe [(Int,Int)] -> Maybe [(Int,Int)]
ins n w Nothing = Just [(n,w)]
ins n w (Just nws) = Just ((n,w):nws)
--
chk :: Int -> M.IntMap [(Int,Int)] -> Int -> Int -> Int -> Bool
chk n grp l r d = path d n grp l r
--
path d n grp l r = runST $ do
    nf <- VM.replicate n False :: ST s (VM.STVector s Bool)
    dfs d grp r nf [] $ SQ.singleton (l,0)
--
dfs :: Int -> M.IntMap [(Int,Int)] -> Int -> VM.STVector s Bool -> [Int] -> SQ.Seq (Int,Int) -> ST s Bool
dfs _ _ _ _  ac (SQ.viewl -> SQ.EmptyL) = return True
dfs d grp r nf ac (SQ.viewl -> (n,w) :< q) =
    if n==r
        then if d==w then dfs d grp r nf (w:ac) q else return False
        else do
            f <- VM.unsafeRead nf n
            VM.unsafeWrite nf n True
            if f
                then dfs d grp r nf ac q
                else dfs d grp r nf ac $ foldl (flip (<|)) q $ map (\(a,b)->(a,b+w)) (grp M.! n)

Score : 400 points

Problem Statement

There are N people standing on the x-axis.
Let the coordinate of Person i be x_i.
For every i, x_i is an integer between 0 and 10^9 (inclusive).
It is possible that more than one person is standing at the same coordinate.

You will given M pieces of information regarding the positions of these people.
The i-th piece of information has the form (L_i, R_i, D_i).
This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.

It turns out that some of these M pieces of information may be incorrect.
Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.

Constraints

1 \leq N \leq 100 000

0 \leq M \leq 200 000

1 \leq L_i, R_i \leq N (1 \leq i \leq M)

0 \leq D_i \leq 10 000 (1 \leq i \leq M)

L_i \neq R_i (1 \leq i \leq M)

If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).

D_i are integers.

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M

Output

If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print Yes; if it does not exist, print No.

Sample Input 1

3 3
1 2 1
2 3 1
1 3 2

Sample Output 1

Yes

Some possible sets of values (x_1, x_2, x_3) are (0, 1, 2) and (101, 102, 103).

Sample Input 2

3 3
1 2 1
2 3 1
1 3 5

Sample Output 2

No

If the first two pieces of information are correct, x_3 - x_1 = 2 holds, which is contradictory to the last piece of information.

Sample Input 3

4 3
2 1 1
2 3 5
3 4 2

Sample Output 3

Yes

Sample Input 4

10 3
8 7 100
7 9 100
9 8 100

Sample Output 4

No

Sample Input 5

100 0

Sample Output 5

Yes


{-# OPTIONS_GHC -O #-}

import Control.Monad
import Control.Monad.ST
import Data.List
import Data.Maybe
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as VM
import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap as M

main = do
    (n:m:_)<-map read.words<$>getLine::IO [Int]
    lrds <- replicateM m $ unfoldr (B.readInt.B.dropWhile(==' ')) <$> B.getLine :: IO[[Int]]
    --
    let res = solve n lrds
    case res of
        Nothing -> return ()
        Just (uf,dt) -> print uf >> print dt
    --
    putStrLn $ case res of
        Nothing -> "No"
        Just (uf, dt) | chk uf dt -> "Yes"
        _ -> "No"
--
chk uf dt = all (\(a,b) -> (b-a) <= 1000000000) $ M.elems md
    where
        md = foldl (\m i -> M.alter (mf (dt V.! i)) (uf V.! i) m) M.empty [1..V.length uf-1]
        mf d Nothing = Just (min 0 d, max 0 d)
        mf d (Just (a,b)) = Just (min a d, max b d)
--
solve :: Int -> [[Int]] -> Maybe (V.Vector Int, V.Vector Int)
solve n lrds = runST $ do
    uf <- VM.replicate (n+1) (-1) :: ST s (VM.STVector s Int)
    dt <- VM.replicate (n+1) 0 :: ST s (VM.STVector s Int)
    --
    ins uf dt lrds
--
ins uf dt [] = do
    forM_ [1..VM.length uf-1] $ findUF uf dt
    forM_ [1..VM.length uf-1] $ \i -> do
        p <- VM.unsafeRead uf i
        when (p == (-1)) $ VM.unsafeWrite uf i i
    uf' <- V.freeze uf
    dt' <- V.freeze dt
    return $ Just (uf',dt')

ins uf dt ((l:r:d:_):lrds) = do
    (lp,ld) <- findUF uf dt l
    (rp,rd) <- findUF uf dt r
    case (lp,rp) of
        (a,b) | a/=b -> VM.unsafeWrite uf r l >> VM.unsafeWrite dt r (d-rd) >> ins uf dt lrds
        (a,b) | rd-ld == d -> ins uf dt lrds
        _ -> return Nothing

--
findUF :: VM.STVector s Int -> VM.STVector s Int -> Int -> ST s (Int,Int)
findUF uf dt x = do
    p <- VM.unsafeRead uf x
    d <- VM.unsafeRead dt x
    if p == -1
        then return (x,0)
        else do
                (f,v) <- findUF uf dt p
                VM.unsafeWrite uf x f
                VM.unsafeWrite dt x (d+v)
                return (f,d+v)


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

readString = map BS.unpack . BS.words
getString = readString <$> BS.getLine

isqrt :: Int -> Int
isqrt = floor . sqrt . fromIntegral

main = do
  [a, b] <- getString
  let x = read (a ++ b) :: Int
  let x_sqrt = isqrt x
  if x_sqrt ^ 2 == x then
    putStrLn "Yes"
  else
    putStrLn "No"

Score : 200 points

Problem Statement

AtCoDeer the deer has found two positive integers, a and b.
Determine whether the concatenation of a and b in this order is a square number.

Constraints

1 ≤ a,b ≤ 100

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If the concatenation of a and b in this order is a square number, print Yes; otherwise, print No.

Sample Input 1

1 21

Sample Output 1

Yes

As 121 = 11 × 11, it is a square number.

Sample Input 2

100 100

Sample Output 2

No

100100 is not a square number.

Sample Input 3

12 10

Sample Output 3

No


main = read.concat.words<$>getLine>>= \n->putStrLn$if(==n).(^2).floor.sqrt.fromIntegral$n then "Yes" else "No"


main = do
    [a,b] <- words <$> getLine :: IO [String]
    let n = (read :: String -> Float) $ a++b
    putStrLn $ if (sqrt n)*(sqrt n) == n then "Yes"  else "No"


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

main :: IO()
main = do
    [a, b] <- words <$> getLine
    printf "%s" $ slv a b

slv :: String -> String -> String
slv a b | last checkList == val = "Yes"
        | otherwise = "No"
  where val = read (a ++ b) :: Integer
        checkList = takeWhile (<= val) [x*x | x <- [1..]]


import Data.Bool

main :: IO ()
main = do
  (a:b:_) <- map read . words <$> getLine
  putStr $ solve a b

solve :: Int -> Int -> String
solve a b = bool "No" "Yes" $ isSqNum $ connect a b

isSqNum :: Int -> Bool
isSqNum x = x `elem` sqNums

sqNums :: [Int]
sqNums = [ x ^ 2 | x <- [0 .. 1000] ]

connect :: Int -> Int -> Int
connect a b = a * k + b
  where k = head [ 10 ^ i | i <- [0 ..], 10 ^ i > b ]


import Control.Monad

data Travel = Travel {
    time  :: Int,
    x :: Int,
    y :: Int
    } deriving (Show, Eq)

main :: IO ()
main = do
    n <- read <$> getLine :: IO Int
    travel <- forM [1..n] ( \_ -> do
            [t, x, y] <- map read . words <$> getLine :: IO [Int]
            return $ Travel t x y
        )
    putStrLn $ if move travel $ Travel 0 0 0 then "Yes" else "No"

move :: [Travel]
     -> Travel -- current status
     -> Bool
move [] _ = True
move ((Travel time x y):xs) (Travel ctime cx cy) = let
    canMove = (abs (cx - x) + abs (cx - x)) <= time - ctime :: Bool
    nextStates = Travel ctime cx cy :: Travel
    in canMove && move xs nextStates

Score : 300 points

Problem Statement

AtCoDeer the deer is going on a trip in a two-dimensional plane.
In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i.

If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1,y), (x,y+1) and (x,y-1).
Note that he cannot stay at his place.
Determine whether he can carry out his plan.

Constraints

1 ≤ N ≤ 10^5

0 ≤ x_i ≤ 10^5

0 ≤ y_i ≤ 10^5

1 ≤ t_i ≤ 10^5

t_i < t_{i+1} (1 ≤ i ≤ N-1)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
t_1 x_1 y_1
t_2 x_2 y_2
:
t_N x_N y_N

Output

If AtCoDeer can carry out his plan, print Yes; if he cannot, print No.

Sample Input 1

2
3 1 2
6 1 1

Sample Output 1

Yes

For example, he can travel as follows: (0,0), (0,1), (1,1), (1,2), (1,1), (1,0), then (1,1).

Sample Input 2

1
2 100 100

Sample Output 2

No

It is impossible to be at (100,100) two seconds after being at (0,0).

Sample Input 3

2
5 1 1
100 1 1

Sample Output 3

No


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Maybe
import Data.List
import qualified Data.Vector.Unboxed as VU
-- import qualified Data.Vector.Unboxed.Mutable as VUM
-- import Control.Monad
-- import Control.Monad.ST
-- import Debug.Trace
trace _ = id

data Plane = Plane {p_rx::Int, p_ry::Int, p_z0::Int}
           deriving (Eq, Ord, Show)

solve :: Int -> Int -> [[Int]] ->
         Maybe (Int, Int, [(Int, Int, String)], Int, Int)
solve a b d | possible = Just build
            | otherwise = Nothing
  where
    vd = VU.fromListN (a*b) (concat d)
    enc x y = (x-1) * b + (y-1)
    valyx x y | trace ("valyx" ++ show (x,y)) False = undefined
    valyx x y = vd VU.! (enc (min x a) (min y b))
    tri' = [ptPlane x y | x <- [1..a], y <- [1..b]]
    ptPlane x y = catMaybes [mkPlane x y dx dy | dx <- [-1,1], dy <- [-1,1]]
    mkPlane x y dx dy | trace ("mkPlane(in) " ++ show (x,y,dx,dy)) False
      = undefined
    mkPlane x y dx dy = trace ("mkPlane " ++ show (x,y,dx,dy,ddd)) ddd
      where ddd = mkPlane' x y dx dy
    mkPlane' x y dx dy
      | outRangeX x || outRangeX (x+dx) || outRangeY y || outRangeY (y+dy)
        || rx < 0 || ry < 0 || z0 < 0 || not (checkConvex rx ry z0)
      = Nothing
      | otherwise
      = Just (Plane rx ry z0)
      where v0 = valyx x y
            rx = (valyx (x+dx) y - v0) `div` dx
            ry = (valyx x (y+dy) - v0) `div` dy
            z0 = v0 - rx*x - ry*y
            outRangeX x = x < 1 || (a+1) < x
            outRangeY y = y < 1 || (b+1) < y
    xyPair = [(x,y) | x <- [1..a], y <- [1..b]]
    checkConvex rx ry z0
      = all (\(x,y) -> rx*x + ry*y + z0 >= valyx x y) xyPair

    possible = all (not . null) tri'
    tri = nub $ map minimum tri'
    yMax = maximum $ map p_ry tri
    safeMax [] = 0
    safeMax xs = maximum xs
    lxMax = [safeMax $ map p_rx $ filter ((== ry) . p_ry) tri
            | ry <- [0..yMax]]
    board = [(u+1,v+1,c) | (u,v,c) <- boardM]
    boardM = [connY y | y <- [0..yMax-1]]
             ++ [connX y x | y <- [0..yMax-1], x <- [0 .. (lxMax !! y) - 1]]
             ++ [connP p | p <- tri]
    connY y = (bEncY y, bEncY (y+1), "Y")
    connX y x = (bEncX y x, bEncX y (x+1), "X")
    connP (Plane rx ry z0) = (bEncX ry rx, bEncT, show z0)
    bEncY y = y
    bEncX y 0 = bEncY y
    bEncX y x = (yMax+1) + (accXMax !! y) + (x-1)
    bEncT = (yMax+1) + (accXMax !! (yMax+1))
    accXMax = scanl' (+) 0 lxMax
    build = (bEncT + 1, length board, board, 1, bEncT + 1)

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

tmain :: B.ByteString -> Maybe (Int, Int, [(Int, Int, String)], Int, Int)
tmain cont =
  let remLines0 = map B.words (B.lines cont)
      [bs_a,bs_b]:remLines1 = remLines0
      a = readBInt bs_a
      b = readBInt bs_b
      d = map (map readBInt) remLines1
  in solve a b d

outAnswer :: Maybe (Int, Int, [(Int, Int, String)], Int, Int) -> IO ()
outAnswer Nothing               = putStrLn "Impossible"
outAnswer (Just (n,m,uvcs,s,t)) = do
  putStrLn "Possible"
  putStrLn $ unwords $ map show [n,m]
  putStr $ unlines $ map (\(u,v,s) -> unwords [show u, show v, s]) uvcs
  putStrLn $ unwords $ map show [s,t]

main :: IO ()
main = outAnswer . tmain =<< B.getContents

inp1 = "2 3\n1 2 2\n1 2 3\n"
inp2 = "1 3\n100 50 1\n"
tv1 = tmain $ B.pack inp1
tv2 = tmain $ B.pack inp2

Score : 900 points

Problem Statement

AtCoDeer the deer wants a directed graph that satisfies the following conditions:

The number of vertices, N, is at most 300.

There must not be self-loops or multiple edges.

The vertices are numbered from 1 through N.

Each edge has either an integer weight between 0 and 100 (inclusive), or a label X or Y.

For every pair of two integers (x,y) such that 1 ≤ x ≤ A, 1 ≤ y ≤ B,
the shortest distance from Vertex S to Vertex T in the graph where the edges labeled X have the weight x and the edges labeled Y have the weight y, is d_{x,y}.

Construct such a graph (and a pair of S and T) for him, or report that it does not exist.
Refer to Output section for output format.

Constraints

1 ≤ A,B ≤ 10

1 ≤ d_{x,y} ≤ 100 (1 ≤ x ≤ A, 1 ≤ y ≤ B)

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B
d_{1,1} d_{1,2} .. d_{1,B}
d_{2,1} d_{2,2} .. d_{2,B}
:
d_{A,1} d_{A,2} .. d_{A,B}

Output

If no graph satisfies the condition, print Impossible.

If there exists a graph that satisfies the condition, print Possible in the first line.
Then, in the subsequent lines, print the constructed graph in the following format:

N M
u_1 v_1 c_1
u_2 v_2 c_2
:
u_M v_M c_M
S T

Here, M is the number of the edges, and u_i, v_i, c_i represent edges as follows: there is an edge from Vertex u_i to Vertex v_i whose weight or label is c_i.

Also refer to Sample Outputs.

Sample Input 1

2 3
1 2 2
1 2 3

Sample Output 1

Possible
3 4
1 2 X
2 3 1
3 2 Y
1 3 Y
1 3

Sample Input 2

1 3
100 50 1

Sample Output 2

Impossible