#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
(defmacro dp (name args memo-size &body body)
  (let ((memo (gensym)))
    `(let ((,memo (make-array ,memo-size :initial-element nil)))
       (defun ,name ,args
         (or (aref ,memo ,@args)
             (setf (aref ,memo ,@args)
                   ,@body))))))

(defun split (x str)
  (let ((pos (search x str))
        (size (length x)))
    (if pos
        (cons (subseq str 0 pos)
              (split x (subseq str (+ pos size))))
        (list str))))

(defmacro collect-times (time body)
  `(loop repeat ,time collect ,body))

(defun read-times (time)
  (collect-times time (read)))

(defmacro aif (expr then else)
  `(let ((it ,expr))
     (if it ,then ,else)))

(defmacro awhen (expr &rest then)
  `(aif ,expr (progn ,@then) nil))

(defun comulative (function list &key base)
  (if base
      (comulative function (cons base list))
      (do ((lst (cdr list) (cdr lst))
           (acc (list (car list))))
          ((null lst) (reverse acc))
        (push (funcall function (car acc) (car lst)) acc))))

(defun binary-search (function left right
                      &optional
                        (eps 1)
                        (average-function (lambda (x y) (ash (+ x y) -1))))
  (if (<= (abs (- left right)) eps)
      right
      (let ((mid (funcall average-function left right)))
        (if (funcall function mid)
            (binary-search function left mid eps average-function)
            (binary-search function mid right eps average-function)))))

(defun arithmetic-mean (&rest body)
  (/ (apply #'+ body) (length body)))

(defvar +MOD+ (+ (expt 10 9) 7))

(defun main (d x lst)
  (+ x
     (loop for i in lst
           sum (+ 1 (floor (1- d) i)))))

(let ((n (read))
      (d (read))
      (x (read)))
  (princ (main d x (read-times n))))

Score : 200 points

Problem Statement

Some number of chocolate pieces were prepared for a training camp.
The camp had N participants and lasted for D days.
The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on.
As a result, there were X chocolate pieces remaining at the end of the camp. During the camp, nobody except the participants ate chocolate pieces.

Find the number of chocolate pieces prepared at the beginning of the camp.

Constraints

1 \leq N \leq 100

1 \leq D \leq 100

1 \leq X \leq 100

1 \leq A_i \leq 100 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
D X
A_1
A_2
:
A_N

Output

Find the number of chocolate pieces prepared at the beginning of the camp.

Sample Input 1

3
7 1
2
5
10

Sample Output 1

8

The camp has 3 participants and lasts for 7 days.
Each participant eats chocolate pieces as follows:

The first participant eats one chocolate piece on Day 1, 3, 5 and 7, for a total of four.

The second participant eats one chocolate piece on Day 1 and 6, for a total of two.

The third participant eats one chocolate piece only on Day 1, for a total of one.

Since the number of pieces remaining at the end of the camp is one, the number of pieces prepared at the beginning of the camp is 1 + 4 + 2 + 1 = 8.

Sample Input 2

2
8 20
1
10

Sample Output 2

29

Sample Input 3

5
30 44
26
18
81
18
6

Sample Output 3

56


(let ((n (read))
      (a (make-array 200000 :element-type 'integer
                            :initial-element 0
                            :adjustable t))
      (ans 0))
  (loop for i from 1 upto n
    do (setf (aref a i) (read))
       (setf ans (+ ans (abs (- (aref a i) (aref a (- i 1)))))))
  (setf ans (+ ans (abs (aref a n))))
  (loop for i from 1 upto n
        do (let* ((r (- (aref a i) (aref a (- i 1))))
                  (l (- (aref a (1+ i)) (aref a i)))
                  (temp (* r l))
                  (ret (- ans (* 2 (min (abs r) (abs l))))))
             (format t "~a~%" (cond ((= 0 temp) ans)
                                    ((< 0 temp) ans)
                                    (T ret))))))

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

Score : 300 points

Problem Statement

There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.

You planned a trip along the axis.
In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.

However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.

For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.

Constraints

2 \leq N \leq 10^5

-5000 \leq A_i \leq 5000 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N lines.
In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.

Sample Input 1

3
3 5 -1

Sample Output 1

12
8
10

Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively.
For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows:

For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen.

For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen.

For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen.

Sample Input 2

5
1 1 1 2 0

Sample Output 2

4
4
4
2
4

Sample Input 3

6
-679 -2409 -3258 3095 -3291 -4462

Sample Output 3

21630
21630
19932
8924
21630
19288

Submitted source-code file size, in bytes.

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

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


Score : 100 points

Problem Statement

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


(format t "~A~%" (if (< (+ (read) (read)) (read)) "NO" "YES"))


(let* ((n (read))
       (bcard (loop :repeat n :collect(read-line)))
       (m (read))
       (rcard (loop :repeat m :collect(read-line)))
       (ans nil))
  (setf ans (loop :for k :in bcard :maximize(- (count k bcard :test #'string=) (count k rcard :test #'string=))))
  (if (> 0 ans)
      0
      ans))

Score : 200 points

Problem Statement

Takahashi has N blue cards and M red cards.
A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.

Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will earn 1 yen (the currency of Japan); each time he finds a red card with that string, he will lose 1 yen.

Here, we only consider the case where the string announced by Takahashi and the string on the card are exactly the same. For example, if he announces atcoder, he will not earn money even if there are blue cards with atcoderr, atcode, btcoder, and so on. (On the other hand, he will not lose money even if there are red cards with such strings, either.)

At most how much can he earn on balance?

Note that the same string may be written on multiple cards.

Constraints

N and M are integers.

1 \leq N, M \leq 100

s_1, s_2, ..., s_N, t_1, t_2, ..., t_M are all strings of lengths between 1 and 10 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N
M
t_1
t_2
:
t_M

Output

If Takahashi can earn at most X yen on balance, print X.

Sample Input 1

3
apple
orange
apple
1
grape

Sample Output 1

2

He can earn 2 yen by announcing apple.

Sample Input 2

3
apple
orange
apple
5
apple
apple
apple
apple
apple

Sample Output 2

1

If he announces apple, he will lose 3 yen. If he announces orange, he can earn 1 yen.

Sample Input 3

1
voldemort
10
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort

Sample Output 3

0

If he announces voldemort, he will lose 9 yen. If he announces orange, for example, he can avoid losing a yen.

Sample Input 4

6
red
red
blue
yellow
yellow
red
5
red
red
yellow
green
blue

Sample Output 4

1


(setq n(read))
(setq a(loop for i from 1 to n collect(read-line)))
(setq m(read))
(setq b(loop for i from 1 to m collect(read-line)))
(setq s 0)
(dolist(i a)
  (setq u 0)
  (dolist(j a)(if(string= i j)(incf u)))
  (dolist(j b)(if(string= i j)(decf u)))
  (setq s(max s u)))
(princ s)


#-swank (declaim (optimize (speed 0) (safety 3) (debug 3)))
#+swank (declaim (optimize (speed 3) (safety 0) (debug 0)))

(defconstant +mod+ 1000000007)

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1
        (write obj :stream stream)
      (terpri stream))))

(defmethod fast-sort ((sequence list) &key (test #'<))
  (declare (inline sort)
           (inline sb-impl::stable-sort-list))
  (sort sequence (lambda (x y)
                   (funcall test x y))))

(defmacro read-numbers-to-list (size)
  `(progn
     (when (not (integerp ,size))
       (error "Size must be integer."))
     (when (< ,size 0)
       (error "Size must be plus or zero."))
     (loop repeat ,size collect (read))))

(defmacro read-numbers-to-array (size)
  `(progn
     (when (not (integerp ,size))
       (error "Size must be integer."))
     (when (< ,size 0)
       (error "Size must be plus or zero."))
     (make-array ,size :initial-contents (read-numbers-to-list ,size))))

(defmacro read-numbers-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size))))
       (dotimes (,r ,row-size)
         (dotimes (,c ,column-size)
           (setf (aref ,board ,r ,c) (read))))
       ,board)))

(defmethod make-cumlative-sum ((sequence list))
  (labels ((inner (sequence &optional (acc '(0)))
             (if (null sequence)
                 (reverse acc)
                 (inner (rest sequence) (cons (+ (first sequence)
                                                 (first acc))
                                              acc)))))
    (inner sequence)))

(defmethod make-cumlative-sum ((sequence array))
  (declare (type (simple-array fixnum) sequence))
  (the array
       (let* ((n (length sequence))
              (acc (make-array (1+ n) :element-type 'integer :initial-element 0)))
         (loop for i below n do
              (setf (aref acc (1+ i)) (+ (aref sequence i)
                                         (aref acc i)))
            finally
              (return acc)))))

(defmethod princ-for-each-line ((sequence list))
  (labels ((inner (sequence)
             (if (null sequence)
                 (fresh-line)
                 (progn
                   (fresh-line)
                   (princ (first sequence))
                   (inner (rest sequence))))))
    (inner sequence)))

(defmethod princ-for-each-line ((sequence array))
  (dotimes (i (length sequence))
    (fresh-line)
    (princ (aref sequence i)))
  (fresh-line))

(defmacro with-buffered-stdout (&body body)
  (let ((out (gensym)))
    `(let ((,out (make-string-output-stream :element-type 'base-char)))
       (let ((*standard-output* ,out))
         ,@body)
       (write-string (get-output-stream-string ,out)))))

;;; Write code here

(defun solve (n red-points blue-points)
  (let ((res 0)
        (paired nil))
    (loop repeat n do
         (let ((blue-point (first blue-points)))
           (let ((cand
                  (remove-if (lambda (x)
                               (or (find x paired :test #'equalp)
                                   (>= (first x) (first blue-point))
                                   (>= (rest x) (rest blue-point))))
                             red-points)))
             (when cand
               (push (reduce (lambda (a b)
                               (if (< (rest a) (rest b))
                                   b
                                   a))
                             cand
                             :initial-value '(-1 . -1))
                     paired)
               (incf res))
             (pop blue-points)))
       finally
         (return res))))

(defun main ()
  (let ((n (read)))
    (let ((red-points
           (loop for i below n collect
                (cons (read) (read))))
          (blue-points
           (fast-sort (loop for i below n collect
                           (cons (read) (read)))
                      :test (lambda (a b)
                              (< (first a) (first b))))))
      (format t "~a~%" (solve n red-points blue-points)))))

(main)

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


(dotimes (x 3)
  (princ (char (read-line) x)))

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


#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
(defmacro dp (name args memo-size &body body)
  (let ((memo (gensym)))
    `(let ((,memo (make-array ,memo-size :initial-element nil)))
       (defun ,name ,args
         (or (aref ,memo ,@args)
             (setf (aref ,memo ,@args)
                   ,@body))))))

(defun split (x str)
  (let ((pos (search x str))
        (size (length x)))
    (if pos
        (cons (subseq str 0 pos)
              (split x (subseq str (+ pos size))))
        (list str))))

(defmacro collect-times (time body)
  `(loop repeat ,time collect ,body))

(defun read-times (time)
  (collect-times time (read)))

(defmacro aif (expr then else)
    `(let ((it ,expr))
       ,then
       ,else))

(defun func (x &optional (acc 0))
  (if (zerop x)
      acc
      (func (floor x 10) (+ (* acc 10) (mod x 10)))))

(defun main (a b)
  (loop for i from a to b
        when (= i (func i))
          sum 1))

#-swank
(princ (main (read) (read)))

Score : 200 points

Problem Statement

Find the number of palindromic numbers among the integers between A and B (inclusive).
Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.

Constraints

10000 \leq A \leq B \leq 99999

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the number of palindromic numbers among the integers between A and B (inclusive).

Sample Input 1

11009 11332

Sample Output 1

4

There are four integers that satisfy the conditions: 11011, 11111, 11211 and 11311.

Sample Input 2

31415 92653

Sample Output 2

612


(defun int-to-digit (n &key (base 10)) ;; (int-to-digit 123) => (1 2 3)
  (if (zerop n)
      `(0)
      (labels ((rec (n list)
                 (if (= n 0)
                     list
                     (rec (floor n base) (cons (rem n base) list)))))
        (rec n nil))))

(defun palindromep (n &key (base 10)) ;; (palindromep 12321) => t
  (equal (reverse (int-to-digit n :base base)) (int-to-digit n :base base)))

(defun solver ()
  (let ((a (read)) (b (read)) (count 0))
    (loop for i from a to b do
          (when (palindromep i)
            (incf count)))
    (format t "~a~%" count)))

(solver)


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


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


(let* ((n (read))
       (str (read-line)))
  (if (find #\Y str :test #'char=)
      (princ "Four")
      (princ "Three")))

Score : 200 points

Problem Statement

In Japan, people make offerings called hina arare, colorful crackers, on March 3.

We have a bag that contains N hina arare. (From here, we call them arare.)

It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow.

We have taken out the arare in the bag one by one, and the color of the i-th arare was S_i, where colors are represented as follows - pink: P, white: W, green: G, yellow: Y.

If the number of colors of the arare in the bag was three, print Three; if the number of colors was four, print Four.

Constraints

1 \leq N \leq 100

S_i is P, W, G or Y.

There always exist i, j and k such that S_i=P, S_j=W and S_k=G.

Input

Input is given from Standard Input in the following format:

N
S_1 S_2 ... S_N

Output

If the number of colors of the arare in the bag was three, print Three; if the number of colors was four, print Four.

Sample Input 1

6
G W Y P Y W

Sample Output 1

Four

The bag contained arare in four colors, so you should print Four.

Sample Input 2

9
G W W G P W P G G

Sample Output 2

Three

The bag contained arare in three colors, so you should print Three.

Sample Input 3

8
P Y W G Y W Y Y

Sample Output 3

Four


;; -*- coding:utf-8 -*-

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter O3 '(optimize (speed 3) (safety 0) (debug 0)))
  (defparameter O2 '(optimize (speed 3) (safety 1))))

(defmacro print-line (obj &optional (stream '*standard-output*))
  `(prog1 (princ ,obj ,stream) (terpri ,stream)))

;; Hauptteil
(declaim (inline ensure-function))

(declaim (ftype (function (t) (values function &optional))
                ensure-function))
(defun ensure-function (function-designator)
  (if (functionp function-designator)
      function-designator
      (fdefinition function-designator)))

(defun map-combinations (function sequence &key (start 0) end length (copy t))
  (let* ((end (or end (length sequence)))
         (size (- end start))
         (length (or length size))
         (combination (subseq sequence 0 length))
         (function (ensure-function function)))
    (if (= length size)
        (funcall function combination)
        (flet ((call ()
                 (funcall function (if copy
                                       (copy-seq combination)
                                       combination))))
          (etypecase sequence
            (list
             (labels ((combine-list (c-tail o-tail)
                        (if (not c-tail)
                            (call)
                            (do ((tail o-tail (cdr tail)))
                                ((not tail))
                              (setf (car c-tail) (car tail))
                              (combine-list (cdr c-tail) (cdr tail))))))
               (combine-list combination (nthcdr start sequence))))
            (vector
             (labels ((combine (count start)
                        (if (zerop count)
                            (call)
                            (loop for i from start below end
                                  do (let ((j (- count 1)))
                                       (setf (aref combination j) (aref sequence i))
                                       (combine j (+ i 1)))))))
               (combine length start)))
            (sequence
             (labels ((combine (count start)
                        (if (zerop count)
                            (call)
                            (loop for i from start below end
                                  do (let ((j (- count 1)))
                                       (setf (elt combination j) (elt sequence i))
                                       (combine j (+ i 1)))))))
               (combine length start)))))))
  sequence)

(defconstant +factorial-bisection-range-limit+ 8)

(defun %multiply-range (i j)
  (labels ((bisect (j k)
             (declare (type (integer 1 #.most-positive-fixnum) j k))
             (if (< (- k j) +factorial-bisection-range-limit+)
                 (multiply-range j k)
                 (let ((middle (+ j (truncate (- k j) 2))))
                   (* (bisect j middle)
                      (bisect (+ middle 1) k)))))
           (bisect-big (j k)
             (declare (type (integer 1) j k))
             (if (= j k)
                 j
                 (let ((middle (+ j (truncate (- k j) 2))))
                   (* (if (<= middle most-positive-fixnum)
                          (bisect j middle)
                          (bisect-big j middle))
                      (bisect-big (+ middle 1) k)))))
           (multiply-range (j k)
             (declare (type (integer 1 #.most-positive-fixnum) j k))
             (do ((f k (* f m))
                  (m (1- k) (1- m)))
                 ((< m j) f)
               (declare (type (integer 0 (#.most-positive-fixnum)) m)
                        (type unsigned-byte f)))))
    (if (and (typep i 'fixnum) (typep j 'fixnum))
        (bisect i j)
	(bisect-big i j))))

(declaim (inline factorial))
(defun %factorial (n)
  (if (< n 2)
      1
      (%multiply-range 1 n)))

(defun binomial-coefficient (n k)
  (check-type n (integer 0))
  (check-type k (integer 0))
  (assert (>= n k))
  (if (or (zerop k) (= n k))
      1
      (let ((n-k (- n k)))
        (when (< k n-k)
          (rotatef k n-k))
        (if (= 1 n-k)
            n
            (/ (%multiply-range (+ k 1) n)
	       (%factorial n-k))))))

(deftype unum nil `(integer 0 ,(expt 10 9)))
(defun main ()
  (let* ((n (read))
	 (arr (make-array 5 :element-type 'fixnum :initial-element 0)))
    (dotimes (x n)
      (case (aref (read-line) 0)
	(#\M (incf (aref arr 0)))
	(#\A (incf (aref arr 1)))
	(#\R (incf (aref arr 2)))
	(#\C (incf (aref arr 3)))
	(#\H (incf (aref arr 4)))))
    (let ((sum 0))
      (map-combinations
       #'(lambda (triplet)
	   (incf sum
		 (* (aref triplet 0)
		    (aref triplet 1)
		    (aref triplet 2))))
       arr :length 3)
      (print-line sum))))

#-swank(main)

;; Für Test
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "C:/msys64/usr/bin/cat.exe" '("/dev/clipboard") :output out)))

(defun test ()
  (with-input-from-string (*standard-input* (delete #\return (get-clipbrd)))
    (main)))

;; Für Benchmark
(defparameter *file-path* *load-pathname*)
(defparameter *dir-path* (pathname (directory-namestring *file-path*)))
(defparameter *dat-path* (merge-pathnames "test.dat" *dir-path*))

#+swank
(defun gendat ()
  (with-open-file (out *dat-path*
		       :direction :output :if-exists :supersede)
    ))

(defun bench ()
  (let ((*standard-output* (make-broadcast-stream)))
    (with-open-file (*standard-input* *dat-path*)
      (time (main)))))

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


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           ;; enclose the form with VALUES to avoid being captured by LOOP macro
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
    (let* ((minus nil)
           (result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (setf minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48)
                              (* 10 (the (integer 0 #.(floor most-positive-fixnum 10))
                                         result))))
              (return (if minus (- result) result))))))))

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1 (princ obj stream) (terpri stream))))

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (d (read))
         (coords (make-array (+ 1 (* h w)) :element-type 'list :initial-element nil))
         (potentials (make-array (+ 1 (* h w)) :element-type 'uint31 :initial-element 0)))
    (declare (uint31 h w d))
    (dotimes (i h)
      (dotimes (j w)
        (setf (aref coords (read-fixnum))
              (cons i j))))
    (loop for a from d to (* h w)
          when (and (aref coords a) (aref coords (- a d)))
          do (destructuring-bind (i . j) (aref coords a)
               (destructuring-bind (prev-i . prev-j) (aref coords (- a d))
                 (setf (aref potentials a)
                       (+ (abs (- i prev-i))
                          (abs (- j prev-j))
                          (aref potentials (- a d)))))))
    (let ((q (read)))
      (dotimes (_ q)
        (let ((l (read-fixnum))
              (r (read-fixnum)))
          (println (- (aref potentials r)
                      (aref potentials l))))))))

#-swank (main)

;;;
;;; Test and benchmark
;;;

#+swank
(defun io-equal (in-string out-string &key (function #'main) (test #'equal))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNCTION, and returns true if
the string output to *STANDARD-OUTPUT* is equal to OUT-STRING."
  (labels ((ensure-last-lf (s)
             (if (eql (uiop:last-char s) #\Linefeed)
                 s
                 (uiop:strcat s uiop:+lf+))))
    (funcall test
             (ensure-last-lf out-string)
             (with-output-to-string (out)
               (let ((*standard-output* out))
                 (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                   (funcall function)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

#+swank (defparameter *this-pathname* (uiop:current-lisp-file-pathname))
#+swank (defparameter *dat-pathname* (uiop:merge-pathnames* "test.dat" *this-pathname*))

#+swank
(defun run (&optional thing (out *standard-output*))
  "THING := null | string | symbol | pathname

null: run #'MAIN using the text on clipboard as input.
string: run #'MAIN using the string as input.
symbol: alias of FIVEAM:RUN!.
pathname: run #'MAIN using the text file as input."
  (let ((*standard-output* out))
    (etypecase thing
      (null
       (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
         (main)))
      (string
       (with-input-from-string (*standard-input* (delete #\Return thing))
         (main)))
      (symbol (5am:run! thing))
      (pathname
       (with-open-file (*standard-input* thing)
         (main))))))

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (format out "")))

#+swank
(defun bench (&optional (out (make-broadcast-stream)))
  (time (run *dat-pathname* out)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3 2
1 4 3
2 5 7
8 9 6
1
4 8
"
    "5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 2 3
3 7
1 4
5 2
6 8
2
2 2
2 2
"
    "0
0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5 5 4
13 25 7 15 17
16 22 20 2 9
14 11 12 1 19
10 6 23 8 18
3 21 5 24 4
3
13 13
2 10
13 13
"
    "0
5
0
")))

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).

The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}.

You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by consuming |x-i|+|y-j| magic points.

You now have to take Q practical tests of your ability as a magical girl.

The i-th test will be conducted as follows:

Initially, a piece is placed on the square where the integer L_i is written.

Let x be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer x+D is written, as long as x is not R_i. The test ends when x=R_i.

Here, it is guaranteed that R_i-L_i is a multiple of D.

For each test, find the sum of magic points consumed during that test.

Constraints

1 \leq H,W \leq 300

1 \leq D \leq H×W

1 \leq A_{i,j} \leq H×W

A_{i,j} \neq A_{x,y} ((i,j) \neq (x,y))

1 \leq Q \leq 10^5

1 \leq L_i \leq R_i \leq H×W

(R_i-L_i) is a multiple of D.

Input

Input is given from Standard Input in the following format:

H W D
A_{1,1} A_{1,2} ... A_{1,W}
:
A_{H,1} A_{H,2} ... A_{H,W}
Q
L_1 R_1
:
L_Q R_Q

Output

For each test, print the sum of magic points consumed during that test.

Output should be in the order the tests are conducted.

Sample Input 1

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

Sample Output 1

5

4 is written in Square (1,2).

6 is written in Square (3,3).

8 is written in Square (3,1).

Thus, the sum of magic points consumed during the first test is (|3-1|+|3-2|)+(|3-3|+|1-3|)=5.

Sample Input 2

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

Sample Output 2

0
0

Note that there may be a test where the piece is not moved at all, and there may be multiple identical tests.

Sample Input 3

5 5 4
13 25 7 15 17
16 22 20 2 9
14 11 12 1 19
10 6 23 8 18
3 21 5 24 4
3
13 13
2 10
13 13

Sample Output 3

0
5
0


(let ((h (read))
      (w (read))
      (d (read))
      (co (make-array '(100000 2) :element-type 'integer
                                 :initial-element 0
                                 :adjustable t))
      (dif (make-array '(190000) :element-type 'integer
                                :initial-element 0
                                :adjustable t))
      (temp 0)
      q
      l
      r)
  (dotimes (i h)
    (dotimes (j w)
      (setf temp (read))
      (setf (aref co temp 0) i)
      (setf (aref co temp 1) j)))
  (loop for x from 1 upto d
        do (loop for y from 1
              do (setf temp (+ x (* y d)))
                 while (<= temp (* h w)) do (setf (aref dif temp) (+ (aref dif (- temp d)) (abs (- (aref co temp 0) (aref co (- temp d) 0))) (abs (- (aref co temp 1) (aref co (- temp d) 1)))))))
  (setf q (read))
  (dotimes (x q)
    (setf l (read))
    (setf r (read))
    (format t "~A~%" (- (aref dif r) (aref dif l)))))


(let* ((n (read-line))
    (m (princ-to-string (+ (parse-integer n) 1)))
    (ans 0))
(if (= (length n)1)
    (setq ans n)
    (progn
        (if (not (string= (subseq m 0 1) (subseq n 0 1)))
            (setq ans 1)
        )
        (if (string= (subseq n 0 1) "1")
            (incf ans (* (- (length n) 1) 9))
            (incf ans (+ (* (- (length n) 1) 9) (- (parse-integer (subseq n 0 1))1)))
        )
    )
)
(format t "~A~%" ans)
)

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


(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Utilities for 2D geometry (using complex number)
;;;

(declaim (inline intersect-p))
(defun intersect-p (p1 p2 q1 q2 &optional (eps 0))
  "Returns true iff the line segment from P1 to P2 intersects the one from Q1
to Q2."
  (let* ((p1-x (realpart p1))
         (p1-y (imagpart p1))
         (p2-x (realpart p2))
         (p2-y (imagpart p2))
         (q1-x (realpart q1))
         (q1-y (imagpart q1))
         (q2-x (realpart q2))
         (q2-y (imagpart q2))
         (delta-p-x (- p2-x p1-x))
         (delta-p-y (- p2-y p1-y))
         (delta-q-x (- q2-x q1-x))
         (delta-q-y (- q2-y q1-y))
         (det1 (* (- (* delta-p-x (- q1-y p1-y)) (* delta-p-y (- q1-x p1-x)))
                  (- (* delta-p-x (- q2-y p1-y)) (* delta-p-y (- q2-x p1-x)))))
         (det2 (* (- (* delta-q-x (- p1-y q1-y)) (* delta-q-y (- p1-x q1-x)))
                  (- (* delta-q-x (- p2-y q1-y)) (* delta-q-y (- p2-x q1-x))))))
    (and (<= det1 eps) (<= det2 eps))))

(defun calc-internal-angle (c1 c2)
  (acos (max -1d0 (min 1d0 (/ (+ (* (realpart c1) (realpart c2))
                                 (* (imagpart c1) (imagpart c2)))
                              (* (abs c1) (abs c2)))))))

;; The range of CL:PHASE is (-PI, PI]
(declaim (inline calc-angle))
(defun calc-angle (c1 c2)
  "Returns the anticlockwise angle (in the sense of amplitude) from vector C1 to
vector C2. The range is [0, 2PI)."
  (mod (- (phase c2) (phase c1)) #.(* 2 PI)))

;;;
;;; 2D convex hull of points (Monotone Chain Algorithm)
;;; Complexity: O(nlog(n))
;;;

(declaim (inline make-convex-hull!))
(defun make-convex-hull! (points &optional (eps 0))
  "Returns a vector of the vertices comprising the convex hull, which are sorted
in the anticlockwise direction around the perimeter. This function sorts POINTS
as a side effect.

If EPS is non-negative, three vertices in a straight line are excluded (when the
calculation error is within EPS, of course); they are allowed if EPS is
negative.

POINTS := vector of complex number"
  (declare (inline sort)
           (vector points))
  ;; FIXME: the returned vector may contain duplicate vertices in a degenerative
  ;; case: E.g. (make-convex-hull! #(#c(1 2) #c(1 2) #c(1 2) #c(1 2)) 1d-9) |->
  ;; #(#C(1 2) #C(1 2))
  (macrolet ((outer (p1 p2)
               `(let ((c1 ,p1)
                      (c2 ,p2))
                  (- (* (realpart c1) (imagpart c2))
                     (* (imagpart c1) (realpart c2))))))
    (when (<= (length points) 1)
      (return-from make-convex-hull! (copy-seq points)))
    (let* ((n (length points))
           (pos 0)
           (res (make-array (* n 2) :element-type (array-element-type points)))
           (points (sort points (lambda (p1 p2)
                                  (if (= (realpart p1) (realpart p2))
                                      (< (imagpart p1) (imagpart p2))
                                      (< (realpart p1) (realpart p2)))))))
      (declare (fixnum pos))
      (do ((i 0 (+ i 1)))
          ((= i n))
        (loop (if (and (> pos 1)
                       (<= (outer (- (aref res (- pos 1)) (aref res (- pos 2)))
                                  (- (aref points i) (aref res (- pos 1))))
                           eps))
                  (decf pos)
                  (return)))
        (setf (aref res pos) (aref points i))
        (incf pos))
      ;; REVIEW: solution to the above mentioned problem?
      ;; (when (<= (abs (- (aref res (- pos 1)) (aref res (- pos 2)))) eps)
      ;;   (decf pos))
      (let ((tmp-pos pos))
        (do ((i (- n 2) (- i 1)))
            ((< i 0))
          (loop (if (and (> pos tmp-pos)
                         (<= (outer (- (aref res (- pos 1)) (aref res (- pos 2)))
                                    (- (aref points i) (aref res (- pos 1))))
                             eps))
                    (decf pos)
                    (return)))
          (setf (aref res pos) (aref points i))
          (incf pos)))
      (adjust-array res (- pos 1)))))

(in-package :cl-user)

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1 (princ obj stream) (terpri stream))))

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (points (make-array n :element-type t))
         (invs (make-hash-table))
         (res (make-array n :element-type 'double-float :initial-element 0d0)))
    (dotimes (i n)
      (let ((p (complex (float (read) 1d0) (float (read) 1d0))))
        (setf (aref points i) p
              (gethash p invs) i)))
    (let* ((convex-hull (make-convex-hull! points 1d-8))
           (len (length convex-hull)))
      #>convex-hull
      (dotimes (i1 len)
        (let ((p0 (aref convex-hull (mod (- i1 1) len)))
              (p1 (aref convex-hull i1))
              (p2 (aref convex-hull (mod (+ i1 1) len))))
          (setf (aref res (gethash p1 invs))
                (/ (- pi (calc-internal-angle (- p0 p1) (- p2 p1)))
                   (* 2 pi)))))
      (map () #'println res))))

#-swank (main)

;;;
;;; Test and benchmark
;;;

#+swank
(defun io-equal (in-string out-string &key (function #'main) (test #'equal))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNCTION, and returns true if
the string output to *STANDARD-OUTPUT* is equal to OUT-STRING."
  (labels ((ensure-last-lf (s)
             (if (eql (uiop:last-char s) #\Linefeed)
                 s
                 (uiop:strcat s uiop:+lf+))))
    (funcall test
             (ensure-last-lf out-string)
             (with-output-to-string (out)
               (let ((*standard-output* out))
                 (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                   (funcall function)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

#+swank (defparameter *this-pathname* (uiop:current-lisp-file-pathname))
#+swank (defparameter *dat-pathname* (uiop:merge-pathnames* "test.dat" *this-pathname*))

#+swank
(defun run (&optional thing (out *standard-output*))
  "THING := null | string | symbol | pathname

null: run #'MAIN using the text on clipboard as input.
string: run #'MAIN using the string as input.
symbol: alias of FIVEAM:RUN!.
pathname: run #'MAIN using the text file as input."
  (let ((*standard-output* out))
    (etypecase thing
      (null
       (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
         (main)))
      (string
       (with-input-from-string (*standard-input* (delete #\Return thing))
         (main)))
      (symbol (5am:run! thing))
      (pathname
       (with-open-file (*standard-input* thing)
         (main))))))

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (format out "")))

#+swank
(defun bench (&optional (out (make-broadcast-stream)))
  (time (run *dat-pathname* out)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
0 0
1 1
"
    "0.5
0.5
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5
0 0
2 8
4 5
2 6
3 10
"
    "0.43160120892732328768
0.03480224363653196956
0.13880483535586193855
0.00000000000000000000
0.39479171208028279727
")))

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


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


(defun card-game (n)
	(let* ((mylist (make-array n))
          (alice 0)
        (bob 0))
          (dotimes (i n)
            (setf (aref mylist i) (read))
           )
     (sort mylist #'>)

	(dotimes (i n)
      (if (zerop (rem i 2))
      	(setf alice (+ alice (aref mylist i)))
      	(setf bob (+ bob (aref mylist i))))

      )
          (- alice bob)
     )
)

(format t "~A~%" (card-game (read)))

Score: 200 points

Problem Statement

We have N cards. A number a_i is written on the i-th card.

Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.

The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score.

Constraints

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

a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores.

Sample Input 1

2
3 1

Sample Output 1

2

First, Alice will take the card with 3. Then, Bob will take the card with 1.
The difference of their scores will be 3 - 1 = 2.

Sample Input 2

3
2 7 4

Sample Output 2

5

First, Alice will take the card with 7. Then, Bob will take the card with 4. Lastly, Alice will take the card with 2. The difference of their scores will be 7 - 4 + 2 = 5. The difference of their scores will be 3 - 1 = 2.

Sample Input 3

4
20 18 2 18

Sample Output 3

18


(princ (loop :for k :in (sort (loop :repeat (read) :collect (read)) #'>)
             :for x := 1 :then (* -1 x)
             :sum (* k x)))


(let(a)(princ(reduce #'(lambda(a b)(- b a))(sort(dotimes(i(read)a)(setq a(cons(read)a)))'<))))


(setq a(read))
(setq b(read))
(setq c(read))
(setq d(read))
(setq e(read))
(setq f(read))
(setq g(read))
(setq h(read))
(setq i(read))
(setq x(+ a (* c -15) (* b 14)))
(setq y(+ d (* f -15) (* e 14)))
(setq z(+ g (* i -15) (* h 14)))
(princ(if(= x y z)"Yes""No"))

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


(let ((c (make-array '(3 3) :element-type 'integer
                            :adjustable t))
      diff1
      diff2
      (ans "Yes"))
  (dotimes (i 3)
    (dotimes (j 3)
      (setf (aref c i j) (read))))
  (setf diff1 (- (aref c 2 1) (aref c 2 0)))
  (setf diff2 (- (aref c 2 2) (aref c 2 1)))
  (dotimes (i 2)
    (if (or (not (equal diff1 (- (aref c i 1) (aref c i 0)))) (not (equal diff2 (- (aref c i 2) (aref c i 1))))) (setf ans "No")))
  (setf diff1 (- (aref c 1 2) (aref c 0 2)))
  (setf diff2 (- (aref c 2 2) (aref c 1 2)))
  (dotimes (i 2)
    (if (or (not (equal diff1 (- (aref c 1 i) (aref c 0 i)))) (not (equal diff2 (- (aref c 2 i) (aref c 1 i))))) (setf ans "No")))
  (format t "~A~%" ans))


(let* ((h (read))
       (w (read))
       (instr (make-array h :element-type 'string
                            :adjustable t
                            :fill-pointer 0))
       (mp (make-array '(50 50) :element-type 'integer
                                :initial-element -1))
       (white 0)
       (que '((0 0))))
  (dotimes (i h)
    (setf (aref instr i) (read-line))
    (dotimes (j w)
      (if (equal #\. (char (aref instr i) j)) (setf white (1+ white)))))
  (setf (aref mp 0 0) 0)
  (loop for x from 0 upto 2
        when (> (length que) 0) do (let ((a (car (car que)))
                                         (b (elt (car que) 1)))
                                     ;(format t "~A~A~%" a b)
                                     (if (> a 0) (if (and (not (equal (char (aref instr (- a 1)) b) #\#)) (equal (aref mp (- a 1) b) -1))
                                                     (progn (setf (aref mp (- a 1) b) (1+ (aref mp a b)))
                                                            (setf que (append que (list (list (- a 1) b)))))))
                                     (if (> b 0) (if (and (not (equal (char (aref instr a) (- b 1)) #\#)) (equal (aref mp a (- b 1)) -1))
                                                     (progn (setf (aref mp a (- b 1)) (1+ (aref mp a b)))
                                                            (setf que (append que (list (list a (- b 1))))))))
                                     (if (< a (- h 1)) (if (and (not (equal (char (aref instr (+ a 1)) b) #\#)) (equal (aref mp (+ a 1) b) -1))
                                                     (progn (setf (aref mp (+ a 1) b) (1+ (aref mp a b)))
                                                            (setf que (append que (list (list (+ a 1) b)))))))
                                     (if (< b (- w 1)) (if (and (not (equal (char (aref instr a) (+ b 1)) #\#)) (equal (aref mp a (+ b 1)) -1))
                                                     (progn (setf (aref mp a (+ b 1)) (1+ (aref mp a b)))
                                                            (setf que (append que (list (list a (+ b 1)))))))))
                                   (setf que (cdr que))
                                   (setf x 0))
  (format t "~A~%" (if (not (equal -1 (aref mp (- h 1) (- w 1)))) (- white (1+ (aref mp (- h 1) (- w 1)))) -1)))

Score: 400 points

Problem statement

We have an H \times W grid whose squares are painted black or white. The square at the i-th row from the top and the j-th column from the left is denoted as (i, j).

Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1). The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares.

Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W). Also, changes of color must all be carried out before the beginning of the game.

When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares.

The color of the squares are given to you as characters s_{i, j}. If square (i, j) is initially painted by white, s_{i, j} is .; if square (i, j) is initially painted by black, s_{i, j} is #.

Constraints

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

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

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

s_{1, 1} and s_{H, W} are ..

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

Print the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed.

Sample Input 1

3 3
..#
#..
...

Sample Output 1

2

The score 2 can be achieved by changing the color of squares as follows:

Sample Input 2

10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
.....................................

Sample Output 2

209


(defun solve (x y)
  (if (= (mod x y) 0)
    -1
    (loop for i from x by x unless (= (mod i y) 0) return i)))

(princ (solve (read) (read)))

Score : 100 points

Problem Statement

You are given positive integers X and Y.
If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it.
If it does not exist, print -1.

Constraints

1 ≤ X,Y ≤ 10^9

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, or print -1 if it does not exist.

Sample Input 1

8 6

Sample Output 1

16

For example, 16 is a multiple of 8 but not a multiple of 6.

Sample Input 2

3 3

Sample Output 2

-1

A multiple of 3 is a multiple of 3.


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil nil t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare #.OPT)
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
    (let* ((minus nil)
           (result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (setf minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48)
                              (* 10 (the (integer 0 #.(floor most-positive-fixnum 10)) result))))
              (return (if minus (- result) result))))))))

;;;
;;; Disjoint set by Union-Find algorithm
;;;

(defstruct (disjoint-set
            (:constructor make-disjoint-set
                (size &aux (data (make-array size :element-type 'fixnum :initial-element -1))))
            (:conc-name ds-))
  (data nil :type (simple-array fixnum (*))))

(declaim (ftype (function * (values (mod #.array-total-size-limit) &optional)) ds-root))
(defun ds-root (disjoint-set x)
  "Returns the root of X."
  (declare (optimize (speed 3))
           ((mod #.array-total-size-limit) x))
  (let ((data (ds-data disjoint-set)))
    (if (< (aref data x) 0)
        x
        (setf (aref data x)
              (ds-root disjoint-set (aref data x))))))

(declaim (inline ds-unite!))
(defun ds-unite! (disjoint-set x1 x2)
  "Destructively unites X1 and X2 and returns true iff X1 and X2 become
connected for the first time."
  (let ((root1 (ds-root disjoint-set x1))
        (root2 (ds-root disjoint-set x2)))
    (unless (= root1 root2)
      (let ((data (ds-data disjoint-set)))
        ;; ensure the size of root1 >= the size of root2
        (when (> (aref data root1) (aref data root2))
          (rotatef root1 root2))
        (incf (aref data root1) (aref data root2))
        (setf (aref data root2) root1)))))

(declaim (inline ds-connected-p))
(defun ds-connected-p (disjoint-set x1 x2)
  "Returns true iff X1 and X2 have the same root."
  (= (ds-root disjoint-set x1) (ds-root disjoint-set x2)))

(declaim (inline ds-size))
(defun ds-size (disjoint-set x)
  "Returns the size of the connected component to which X belongs."
  (- (aref (ds-data disjoint-set)
           (ds-root disjoint-set x))))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

;;;
;;; Binary heap
;;;

(define-condition heap-empty-error (simple-error)
  ((heap :initarg :heap :reader heap-empty-error-heap))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to pop empty heap ~W" (heap-empty-error-heap condition)))))

(define-condition heap-full-error (simple-error)
  ((heap :initarg :heap :reader heap-full-error-heap)
   (item :initarg :item :reader heap-full-error-item))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to push item ~W to full heap ~W"
             (heap-full-error-item condition)
             (heap-full-error-heap condition)))))

(defmacro define-binary-heap (name &key (order '#'>) (element-type 'fixnum))
  "Defines the binary heap specialized for the given order and the element
type. This macro defines a structure of the name NAME and relevant functions:
MAKE-<NAME>, <NAME>-PUSH, <NAME>-POP, <NAME>-REINITIALIZE, <NAME>-EMPTY-P,
<NAME>-COUNT, and <NAME>-PEEK."
  (check-type name symbol)
  (let* ((string-name (string name))
         (fname-push (intern (format nil "~A-PUSH" string-name)))
         (fname-pop (intern (format nil "~A-POP" string-name)))
         (fname-reinitialize (intern (format nil "~A-REINITIALIZE" string-name)))
         (fname-empty-p (intern (format nil "~A-EMPTY-P" string-name)))
         (fname-count (intern (format nil "~A-COUNT" string-name)))
         (fname-peek (intern (format nil "~A-PEEK" string-name)))
         (fname-make (intern (format nil "MAKE-~A" string-name)))
         (acc-position (intern (format nil "~A-POSITION" string-name)))
         (acc-data (intern (format nil "~A-DATA" string-name))))
    `(progn
       (defstruct (,name
                   (:constructor ,fname-make
                       (size
                        &aux (data ,(if (eql element-type '*)
                                        `(make-array (1+ size))
                                        `(make-array (1+ size) :element-type ',element-type))))))
         (data #() :type (simple-array ,element-type (*)) :read-only t)
         (position 1 :type (integer 1 #.most-positive-fixnum)))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-push))
       (defun ,fname-push (obj heap)
         "Adds OBJ to the end of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((update (pos)
                        (declare (optimize (speed 3) (safety 0)))
                        (unless (= pos 1)
                          (let ((parent-pos (ash pos -1)))
                            (when (funcall ,order (aref data pos) (aref data parent-pos))
                              (rotatef (aref data pos) (aref data parent-pos))
                              (update parent-pos))))))
               (unless (< position (length data))
                 (error 'heap-full-error :heap heap :item obj))
               (setf (aref data position) obj)
               (update position)
               (incf position)
               heap))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-pop))
       (defun ,fname-pop (heap)
         "Removes and returns the element at the top of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((update (pos)
                        (declare (optimize (speed 3) (safety 0))
                                 ((integer 1 #.most-positive-fixnum) pos))
                        (let* ((child-pos1 (+ pos pos))
                               (child-pos2 (1+ child-pos1)))
                          (when (<= child-pos1 position)
                            (if (<= child-pos2 position)
                                (if (funcall ,order (aref data child-pos1) (aref data child-pos2))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                      (rotatef (aref data pos) (aref data child-pos1))
                                      (update child-pos1))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos2))
                                      (rotatef (aref data pos) (aref data child-pos2))
                                      (update child-pos2)))
                                (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                  (rotatef (aref data pos) (aref data child-pos1))))))))
               (when (= position 1)
                 (error 'heap-empty-error :heap heap))
               (prog1 (aref data 1)
                 (decf position)
                 (setf (aref data 1) (aref data position))
                 (update 1))))))

       (declaim (inline ,fname-reinitialize))
       (defun ,fname-reinitialize (heap)
         "Makes HEAP empty."
         (setf (,acc-position heap) 1)
         heap)

       (declaim (inline ,fname-empty-p))
       (defun ,fname-empty-p (heap)
         "Returns true iff HEAP is empty."
         (= 1 (,acc-position heap)))

       (declaim (inline ,fname-count))
       (defun ,fname-count (heap)
         "Returns the current number of the elements in HEAP."
         (- (,acc-position heap) 1))

       (declaim (inline ,fname-peek))
       (defun ,fname-peek (heap)
         "Returns the topmost element of HEAP."
         (if (= 1 (,acc-position heap))
             (error 'heap-empty-error :heap heap)
             (aref (,acc-data heap) 1))))))

;;;
;;; Meldable heap (pairing heap)
;;;
;;; Reference:
;;; https://topcoder.g.hatena.ne.jp/spaghetti_source/20120929/1348886107
;;;

;; Note: An empty heap is NIL.
;; TODO: handle the order of heap independently
(defstruct (pheap (:constructor %make-pheap (key))
                  (:conc-name %pheap-)
                  (:copier nil)
                  (:predicate nil))
  (key nil :type uint62)
  (next nil :type (or null pheap))
  (head nil :type (or null pheap)) ; head of children
  )

(declaim (inline pheap-merge))
(defun pheap-merge (node1 node2 order)
  (cond ((null node1) node2)
        ((null node2) node1)
        (t
         ;; ensure NODE1 < NODE2
         (when (funcall order (%pheap-key node2) (%pheap-key node1))
           (rotatef node1 node2))
         (setf (%pheap-next node2) (%pheap-head node1)
               (%pheap-head node1) node2)
         node1)))

(declaim (inline %pheap-merge-list1 %pheap-merge-list2 %pheap-merge-list3))

;; NOTE: Three implementations are available for MERGE-LIST, each of which has
;; good points and bad points.

;; Implementation 1, naive recursion
;; Pros: fastest on SBCL, no consing
;; Cons: there is a risk of stack exhaustion

(defun %pheap-merge-list1 (node order)
  (labels ((recur (node)
             (when node
               (let* ((a node)
                      (b (%pheap-next node)))
                 (if b
                     (let ((next (%pheap-next b)))
                       (setf (%pheap-next b) nil)
                       (let ((a+b (pheap-merge a b order)))
                         (pheap-merge a+b (recur next) order)))
                     a)))))
    (recur node)))

;; Implementation 2, manual stack by list
;; Pros: stack safe
;; Cons: most consing, 15% slower

(defun %pheap-merge-list2 (node order)
  (let (stack)
    (loop
      (unless node (return))
      (let ((a node)
            b)
        (setf node (%pheap-next node)
              (%pheap-next a) nil)
        (when node
          (setf b node
                node (%pheap-next node)
                (%pheap-next b) nil))
        (push (pheap-merge a b order) stack)))
    (dolist (part stack)
      (setf node (pheap-merge part node order)))
    node))

;; Implementation 3, manual stack by PHEAP
;; Pros: stack safe, no consing
;; Cons: a bit trickey, 5% slower

(defun %pheap-merge-list3 (node order)
  (let ((stack (load-time-value (sb-mop:class-prototype (find-class 'pheap)))))
    (setf (%pheap-next stack) nil)
    (loop
      (unless node (return))
      (let ((a node)
            b)
        (setf node (%pheap-next node)
              (%pheap-next a) nil)
        (when node
          (setf b node
                node (%pheap-next node)
                (%pheap-next b) nil))
        (setf a (pheap-merge a b order)
              (%pheap-next a) (%pheap-next stack)
              (%pheap-next stack) a)))
    (loop
      (unless (%pheap-next stack) (return))
      (let ((next (%pheap-next stack)))
        (setf (%pheap-next stack)
              (%pheap-next (%pheap-next stack)))
        (setf node (pheap-merge next node order))))
    node))

(declaim (inline pheep-peek))
(defun pheap-peek (node)
  (%pheap-key node))

;; Here we adopt clojure-like terms CONJ/DISJ as these are not operations to
;; make use of side effects, unlike PUSH/POP.
(declaim (inline pheap-conj))
(defun pheap-conj (node key order)
  (pheap-merge node (%make-pheap key) order))

(declaim (inline pheap-disj))
(defun pheap-disj (node order)
  (declare (pheap node))
  (%pheap-merge-list3 (%pheap-head node) order))

(defmacro pheap-push (key node order)
  `(setf ,node (pheap-conj ,node ,key ,order)))

(defmacro pheap-pop (node order)
  `(prog1 (pheap-peek ,node)
     (setf ,node (pheap-disj ,node ,order))))

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1 (princ obj stream) (terpri stream))))

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(define-binary-heap heap
  :order (lambda (p1 p2)
           (< (the uint62 (pheap-peek p1))
              (the uint62 (pheap-peek p2))))
  :element-type pheap)

(defun main ()
  (let* ((n (read))
         (m (read))
         (as (make-array n :element-type 'uint32))
         (comps (make-array n :element-type '(or null pheap) :initial-element nil))
         (dset (make-disjoint-set n))
         (que (make-heap n))
         (res 0))
    (declare (uint32 n m)
             (uint62 res))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)))
    (dotimes (i m)
      (let ((x (read-fixnum))
            (y (read-fixnum)))
        (ds-unite! dset x y)))
    (dotimes (i n)
      (let ((root (ds-root dset i)))
        (pheap-push (aref as i) (aref comps root) #'<)))
    (dotimes (i n)
      (when (aref comps i)
        (heap-push (aref comps i) que)))
    (loop
      (let* ((comp1 (heap-pop que))
             (a1 (pheap-pop comp1 #'<)))
        (when (heap-empty-p que)
          (println res)
          (return-from main))
        (let* ((comp2 (heap-pop que))
               (a2 (pheap-pop comp2 #'<)))
          (incf res (+ a1 a2))
          (let ((new-comp (pheap-merge comp1 comp2 #'<)))
            (when (and (null new-comp)
                       (not (heap-empty-p que)))
              (write-line "Impossible")
              (return-from main))
            (heap-push new-comp que)))))))

#-swank (main)

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.


(defun buying-sweets ()
  (let ((x (read))
        (a (read))
        (b (read)))
    (setf x (- x a))
    (loop while (<= 0 (- x b))
          do (decf x b))
    x))

(format t "~D~%" (buying-sweets))

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


#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           ;; enclose the form with VALUES to avoid being captured by LOOP macro
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)
#-swank (disable-debugger) ; for CS Academy

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (declare #.OPT)
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
    (let* ((minus nil)
           (result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (setf minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48)
                              (* 10 (the (integer 0 #.(floor most-positive-fixnum 10))
                                         result))))
              (return (if minus (- result) result))))))))

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1 (princ obj stream) (terpri stream))))

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +nan+ most-positive-fixnum)

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (m (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (pots (make-array n :element-type 'fixnum :initial-element +nan+)))
    (declare (uint31 n m))
    (dotimes (i m)
      (let ((l (- (read-fixnum) 1))
            (r (- (read-fixnum) 1))
            (d (read-fixnum)))
        (push (cons r d) (aref graph l))
        (push (cons l (- d)) (aref graph r))))
    (labels
        ((dfs (v potential)
           (declare (fixnum v potential))
           (if (= +nan+ (aref pots v))
               (progn
                 (setf (aref pots v) potential)
                 (loop for (next . delta) of-type (fixnum . fixnum) in (aref graph v)
                       do (dfs next (+ potential delta))))
               (unless (= (aref pots v) potential)
                 (write-line "No")
                 (return-from main)))))
      (dotimes (i n)
        (when (= +nan+ (aref pots i))
          (dfs i 0)))
      (write-line "Yes"))))

#-swank (main)

;;;
;;; Test and benchmark
;;;

#+swank
(defun io-equal (in-string out-string &key (function #'main) (test #'equal))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNCTION, and returns true if
the string output to *STANDARD-OUTPUT* is equal to OUT-STRING."
  (labels ((ensure-last-lf (s)
             (if (eql (uiop:last-char s) #\Linefeed)
                 s
                 (uiop:strcat s uiop:+lf+))))
    (funcall test
             (ensure-last-lf out-string)
             (with-output-to-string (out)
               (let ((*standard-output* out))
                 (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                   (funcall function)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    ;; (run-program "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe" '("get-clipboard") :output out)
    (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)))

#+swank (defparameter *this-pathname* (uiop:current-lisp-file-pathname))
#+swank (defparameter *dat-pathname* (uiop:merge-pathnames* "test.dat" *this-pathname*))

#+swank
(defun run (&optional thing (out *standard-output*))
  "THING := null | string | symbol | pathname

null: run #'MAIN using the text on clipboard as input.
string: run #'MAIN using the string as input.
symbol: alias of FIVEAM:RUN!.
pathname: run #'MAIN using the text file as input."
  (let ((*standard-output* out))
    (etypecase thing
      (null
       (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
         (main)))
      (string
       (with-input-from-string (*standard-input* (delete #\Return thing))
         (main)))
      (symbol (5am:run! thing))
      (pathname
       (with-open-file (*standard-input* thing)
         (main))))))

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (format out "")))

#+swank
(defun bench (&optional (out (make-broadcast-stream)))
  (time (run *dat-pathname* out)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3
1 2 1
2 3 1
1 3 2
"
    "Yes
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3
1 2 1
2 3 1
1 3 5
"
    "No
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 3
2 1 1
2 3 5
3 4 2
"
    "Yes
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10 3
8 7 100
7 9 100
9 8 100
"
    "No
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "100 0
"
    "Yes
")))

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


#-swank
(unless (member :child-sbcl *features*)
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))

(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx opt
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) `(values ,(read s nil nil t)))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~A" b)) () '(unsigned-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~A" b)) () '(signed-byte ,b))) bits)))
(define-int-types 2 4 7 8 15 16 31 32 62 63 64)

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (declare #.opt)
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
    (let* ((minus nil)
           (result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (setq minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48)
                              (* 10 (the (integer 0 #.(floor most-positive-fixnum 10))
                                         result))))
              (return (if minus (- result) result))))))))

(in-package :cl-user)

(defmacro dbg (&rest forms)
  #+swank
  (if (= (length forms) 1)
      `(format *error-output* "~A => ~A~%" ',(car forms) ,(car forms))
      `(format *error-output* "~A => ~A~%" ',forms `(,,@forms)))
  #-swank (declare (ignore forms)))

(declaim (inline println))
(defun println (obj &optional (stream *standard-output*))
  (let ((*read-default-float-format* 'double-float))
    (prog1 (princ obj stream) (terpri stream))))

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +nan+ #x7fffffff)

(defun main ()
  (declare #.opt)
  (let* ((n (read))
         (m (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (potentials (make-array n :element-type 'int32 :initial-element +nan+)))
    (declare (uint31 n m))
    (dotimes (i m)
      (let ((l (- (read-fixnum) 1))
            (r (- (read-fixnum) 1))
            (d (read-fixnum)))
        (push (cons r d) (aref graph l))
        (push (cons l (- d)) (aref graph r))))
    (labels ((dfs (v pot)
               (cond ((= +nan+ (aref potentials v))
                      (setf (aref potentials v) pot)
                      (loop for (next . d) of-type (int32 . int32) in (aref graph v)
                            do (dfs next (+ pot d))))
                     ((/= pot (aref potentials v))
                      (write-line "No")
                      (return-from main)))))
      (dotimes (v n)
        (when (= +nan+ (aref potentials v))
          (dfs v 0)))
      (write-line "Yes"))))

#-swank (main)

;;;
;;; Test and benchmark
;;;

#+swank
(defun io-equal (in-string out-string &key (function #'main) (test #'equal))
  "Passes IN-STRING to *STANDARD-INPUT*, executes FUNCTION, and returns true if
the string output to *STANDARD-OUTPUT* is equal to OUT-STRING."
  (labels ((ensure-last-lf (s)
             (if (eql (uiop:last-char s) #\Linefeed)
                 s
                 (uiop:strcat s uiop:+lf+))))
    (funcall test
             (ensure-last-lf out-string)
             (with-output-to-string (out)
               (let ((*standard-output* out))
                 (with-input-from-string (*standard-input* (ensure-last-lf in-string))
                   (funcall function)))))))

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    #+os-windows (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)
    #+os-unix (run-program "xsel" '("-b" "-o") :output out :search t)))

#+swank (defparameter *this-pathname* (uiop:current-lisp-file-pathname))
#+swank (defparameter *dat-pathname* (uiop:merge-pathnames* "test.dat" *this-pathname*))

#+swank
(defun run (&optional thing (out *standard-output*))
  "THING := null | string | symbol | pathname

null: run #'MAIN using the text on clipboard as input.
string: run #'MAIN using the string as input.
symbol: alias of FIVEAM:RUN!.
pathname: run #'MAIN using the text file as input."
  (let ((*standard-output* out))
    (etypecase thing
      (null
       (with-input-from-string (*standard-input* (delete #\Return (get-clipbrd)))
         (main)))
      (string
       (with-input-from-string (*standard-input* (delete #\Return thing))
         (main)))
      (symbol (5am:run! thing))
      (pathname
       (with-open-file (*standard-input* thing)
         (main))))))

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (format out "")))

#+swank
(defun bench (&optional (out (make-broadcast-stream)))
  (time (run *dat-pathname* out)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3
1 2 1
2 3 1
1 3 2
"
    "Yes
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3
1 2 1
2 3 1
1 3 5
"
    "No
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 3
2 1 1
2 3 5
3 4 2
"
    "Yes
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10 3
8 7 100
7 9 100
9 8 100
"
    "No
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "100 0
"
    "Yes
")))