(let ((n (read))
    (a (read))
    (b (read))
    (s (read-line))
    (ninzuu 0)
    (bi 1))
    (loop for i below n do
        (progn
            (case (char-code (char s i))
                (97 (if (< ninzuu (+ a b))
                    (progn
                        (format t "Yes~%")
                        (incf ninzuu)
                    )
                    (format t "No~%")))
                (98 (if (and (< ninzuu (+ a b)) (<= bi b))
                    (progn
                        (format t "Yes~%")
                        (incf ninzuu)
                        (incf bi)
                    )
                    (format t "No~%")))
                (99 (format t "No~%"))
            )
        )
    )
)

Score : 200 points

Problem Statement

There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.

Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.

A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B.

An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B and the student ranks B-th or above among all overseas students.

A string S is assigned indicating attributes of all participants. If the i-th character of string S is a, this means the participant ranked i-th in the Qualification contests is a Japanese student; b means the participant ranked i-th is an overseas student; and c means the participant ranked i-th is neither of these.

Write a program that outputs for all the participants in descending rank either Yes if they passed the Qualification contests or No if they did not pass.

Constraints

1≦N,A,B≦100000

A+B≦N

S is N characters long.

S consists only of the letters a, b and c.

Input

Inputs are provided from Standard Input in the following form.

N A B
S

Output

Output N lines. On the i-th line, output Yes if the i-th participant passed the Qualification contests or No if that participant did not pass.

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

The first, second, fifth, sixth, and seventh participants pass the Qualification contests.

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

No
Yes
Yes
Yes
Yes
No
Yes
Yes
No
Yes
No
No

The sixth participant is third among overseas students and thus does not pass the Qualification contests.

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No


;; -*- 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 (values) 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))))))))

(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
           (inline sort))
  (let* ((w (read))
         (h (read))
         (ps (make-array w :element-type 'uint31))
         (qs (make-array h :element-type 'uint31)))
    (dotimes (i w)
      (setf (aref ps i) (read-fixnum)))
    (dotimes (j h)
      (setf (aref qs j) (read-fixnum)))
    (setf ps (sort ps #'<)
          qs (sort qs #'<))
    (let ((x (+ w 1))
          (y (+ h 1))
          (i 0)
          (j 0)
          (res 0))
      (declare (uint31 x y i j)
               (uint62 res))
      (loop
        (cond ((and (= i w) (= j h))
               (println res)
               (return-from main))
              ((= i w)
               (incf res (* (aref qs j) x))
               (decf y)
               (incf j))
              ((= j h)
               (incf res (* (aref ps i) y))
               (decf x)
               (incf i))
              (t
               (if (< (aref qs j) (aref ps i))
                   (progn (incf res (* (aref qs j) x))
                          (decf y)
                          (incf j))
                   (progn (incf res (* (aref ps i) y))
                          (decf x)
                          (incf i)))))))))

#-swank (main)

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

Score : 500 points

Problem Statement

On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers.

There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and the difference between the x coordinates is 1.

The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is p_i for any value of j, while the cost of paving a road between houses on coordinates (i,j) and (i,j+1) is q_j for any value of i.

Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.

Constraints

1 ≦ W,H ≦ 10^5

1 ≦ p_i ≦ 10^8(0 ≦ i ≦ W-1)

1 ≦ q_j ≦ 10^8(0 ≦ j ≦ H-1)

p_i (0 ≦ i ≦ W−1) is an integer.

q_j (0 ≦ j ≦ H−1) is an integer.

Input

Inputs are provided from Standard Input in the following form.

W H
p_0
:
p_{W-1}
q_0
:
q_{H-1}

Output

Output an integer representing the minimum total cost.

Sample Input 1

2 2
3
5
2
7

Sample Output 1

29

It is enough to pave the following eight roads.

Road connecting houses at (0,0) and (0,1)

Road connecting houses at (0,1) and (1,1)

Road connecting houses at (0,2) and (1,2)

Road connecting houses at (1,0) and (1,1)

Road connecting houses at (1,0) and (2,0)

Road connecting houses at (1,1) and (1,2)

Road connecting houses at (1,2) and (2,2)

Road connecting houses at (2,0) and (2,1)

Sample Input 2

4 3
2
4
8
1
2
9
3

Sample Output 2

60

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.


;; -*- 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 (values) 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))))))))

(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 (inline sort))
  (let* ((w (read))
         (h (read))
         (ps (make-array w :element-type 'uint32))
         (qs (make-array h :element-type 'uint32)))
    (dotimes (i w)
      (setf (aref ps i) (read-fixnum)))
    (dotimes (j h)
      (setf (aref qs j) (read-fixnum)))
    (setf ps (sort ps #'<)
          qs (sort qs #'<))
    (let ((x (+ w 1))
          (y (+ h 1))
          (i 0)
          (j 0)
          (res 0))
      (loop
        (cond ((and (= i w) (= j h))
               (println res)
               (return-from main))
              ((= i w)
               (incf res (* (aref qs j) x))
               (decf y)
               (incf j))
              ((= j h)
               (incf res (* (aref ps i) y))
               (decf x)
               (incf i))
              (t
               (if (< (aref qs j) (aref ps i))
                   (progn (incf res (* (aref qs j) x))
                          (decf y)
                          (incf j))
                   (progn (incf res (* (aref ps i) y))
                          (decf x)
                          (incf i)))))))))

#-swank (main)


#|
------------------------------------
|               Utils               |
------------------------------------
|#

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

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

(defconstant +mod+ 1000000007)

(defmacro define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~a" b)) () '(signed-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~a" b)) () '(unsigned-byte ,b))) bits)))

(define-int-types 2 4 8 16 32 64)

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

(defmacro safe-sort (list test &key (key #'identity))
  `(progn
    (declaim (inline sort sb-impl::stable-sort-list))
    (sort (copy-seq ,list) ,test :key ,key)))

(defmacro read-numbers-to-list (size)
  `(loop repeat ,size collect (read)))

(defmacro read-numbers-to-array (size)
  (let ((i (gensym))
        (arr (gensym)))
    `(let ((,arr (make-array ,size
                             :element-type 'fixnum)))
       (declare ((array fixnum 1) ,arr))
       (loop for ,i of-type fixnum below ,size do
            (setf (aref ,arr ,i) (read))
          finally
            (return ,arr)))))

(defmacro read-characters-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym))
        (tmp (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size) :element-type 'character :adjustable nil)))
       (dotimes (,r ,row-size ,board)
         (let ((,tmp (read-line)))
           (dotimes (,c ,column-size)
             (setf (aref ,board ,r ,c) (char ,tmp ,c))))))))

(defmethod princ-for-each-line ((sequence list))
  (format t "~{~a~&~}" sequence))

(defmethod princ-for-each-line ((sequence vector))
  (loop for i below (length sequence) do
       (princ (aref sequence i))
       (fresh-line)))

(declaim (inline unwrap))
(defun unwrap (list)
  (the string
       (format nil "~{~a~^ ~}" list)))

(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)))))

(defmacro maxf (place cand)
  `(setf ,place (max ,place ,cand)))

(defmacro minf (place cand)
  `(setf ,place (min ,place ,cand)))

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defun iota (count &optional (start 0) (step 1))
  (loop for i from 0 below count collect (+ start (* i step))))

#|
------------------------------------
|               Body               |
------------------------------------
|#

(defun solve (x)
  (loop for i below (length x)
     with s-cnt = 0
     with res = (length x)
     do
       (if (char-equal (char x i)
                       #\S)
           (incf s-cnt)
           (when (plusp s-cnt)
             (decf res 2)
             (decf s-cnt)))
     finally
       (return res)))

(defun main ()
  (declare #.OPT)
  (let ((x (read-line)))
    (println (solve x))))

#-swank (main)

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


(let ((s (read-line)))
      (format t "~A~%" (concatenate 'string (subseq s 0 4) " " (subseq s 4))))

Score : 100 points

Problem Statement

This contest is CODE FESTIVAL.
However, Mr. Takahashi always writes it CODEFESTIVAL, omitting the single space between CODE and FESTIVAL.

So he has decided to make a program that puts the single space he omitted.

You are given a string s with 12 letters.
Output the string putting a single space between the first 4 letters and last 8 letters in the string s.

Constraints

s contains exactly 12 letters.

All letters in s are uppercase English letters.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string putting a single space between the first 4 letters and last 8 letters in the string s.
Put a line break at the end.

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE FESTIVAL

Putting a single space between the first 4 letters and last 8 letters in CODEFESTIVAL makes it CODE FESTIVAL.

Sample Input 2

POSTGRADUATE

Sample Output 2

POST GRADUATE

Sample Input 3

ABCDEFGHIJKL

Sample Output 3

ABCD EFGHIJKL


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam))
  #-swank (set-dispatch-macro-character #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil (values) t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(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* ((s (coerce (read-line) 'simple-base-string))
         (n (length s))
         (k (read)))
    (declare (uint31 k))
    (labels ((calc-dist (c)
               (if (char= #\a c)
                   0
                   (- 123 (char-code c)))))
      (declare (inline calc-dist))
      (dotimes (i n)
        (let ((dist (calc-dist (aref s i))))
          (when (<= dist k)
            (decf k dist)
            (setf (aref s i) #\a))))
      (setf (aref s (- n 1))
            (code-char (+ 97 (rem (- (+ (char-code (aref s (- n 1))) k) 97) 26))))
      (write-line s))))

#-swank(main)

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam))
  #-swank (set-dispatch-macro-character #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil (values) t))))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(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* ((s (coerce (the (simple-array base-char (*)) (read-line)) 'simple-base-string))
         (n (length s))
         (k (read)))
    (declare (uint31 k))
    (labels ((calc-dist (c)
               (+ 1 (- #.(char-code #\z) (char-code c)))))
      (dotimes (i n)
        (let ((dist (calc-dist (aref s i))))
          (when (<= dist k)
            (decf k dist)
            (setf (aref s i) #\a))))
      (setf (aref s (- n 1))
            (code-char (+ 97 (rem (- (+ (char-code (aref s (- n 1))) k) 97) 26))))
      (write-line s))))

#-swank(main)


(defparameter a (read))
(defparameter b (read))
(defparameter h (read))

(defun trape (x y z)
  (declare (type fixnum x y z)
           (optimize (speed 3) (safety 0)))
  (/ (* (+ x y) z) 2))

(compile 'trape)

(princ (trape a b h))

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

The input is given from Standard Input in the following format:

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


(format t "~s"
        (*
         (+ (parse-integer (read-line))
            (parse-integer (read-line)))
         (/ (parse-integer (read-line)) 2)))


(setq s(loop for i from 1 to 3 collect(map'list #'(lambda(c)(-(char-code c)97))(read-line))))
(setq f 0)
(loop
  (if(null(nth f s))(return))
  (setq v f)
  (setq f(car(nth f s)))
  (setf(nth v s)(cdr(nth v s))))
(princ(code-char(+ f 65)))

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

The input is given from Standard Input in the following format:

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(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* ((s (map '(simple-array uint4 (*)) #'digit-char-p (read-line)))
         (n (length s))
         (res 0))
    (declare ((integer 1 10) n)
             (uint62 res))
    (dotimes (l n)
      (loop for r from l to n
            do (incf res
                     (* (loop with res of-type uint62 = 0
                              for i from l below r
                              do (setf res (+ (the uint62 (* 10 res)) (aref s i)))
                              finally (return res))
                        (if (zerop l)
                            1
                            (expt 2 (- l 1)))
                        (if (= r n)
                            1
                            (expt 2 (- n r 1)))))))
    (println res)))

#-swank(main)

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

The input is given from Standard Input in the following format:

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


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

;; BEGIN_INSERTED_CONTENTS
(defstruct (queue (:constructor make-queue
                    (&optional list &aux (tail (last list)))))
  (list nil :type list)
  (tail nil :type (or null (cons t null))))

(declaim (inline enqueue))
(defun enqueue (obj queue)
  "Pushes OBJ to the end of QUEUE."
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (setf (cdr tail) (list obj)
              tail (cdr tail))))
  queue)

(declaim (inline dequeue))
(defun dequeue (queue)
  "Removes and returns the element at the front of QUEUE. Returns NIL if QUEUE
is empty."
  (pop (queue-list queue)))

(declaim (inline queue-empty-p))
(defun queue-empty-p (queue)
  (null (queue-list queue)))

(declaim (inline enqueue-front))
(defun enqueue-front (obj queue)
  "Pushes OBJ to the front of QUEUE."
  (symbol-macrolet ((list (queue-list queue))
                    (tail (queue-tail queue)))
    (if (null list)
        (setf tail (list obj)
              list tail)
        (push obj list))
    queue))

(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))))))))

(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

(define-modify-macro minf (new-value)
  (lambda (x y) (min x y)))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (m (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (dists (make-hash-table :test #'equal :size (* 2 m)))
         (dist-seq (make-array n :element-type 'uint32 :initial-element #xffffffff))
         ;; ((station . color) . dist)
         (q (make-queue)))
    (declare (uint31 n m))
    (dotimes (i m)
      (let ((p (- (read-fixnum) 1))
            (q (- (read-fixnum) 1))
            (c (read-fixnum)))
        (push (cons q c) (aref graph p))
        (push (cons p c) (aref graph q))))
    (enqueue (cons (cons 0 0) 0) q)
    (setf (gethash (cons (cons 0 0) 0) dists) 0)
    (setf (aref dist-seq 0) 0)
    (loop until (queue-empty-p q)
          for element = (dequeue q)
          for (node . dist) of-type (cons . uint31) = element
          for (station . prevcolor) of-type (uint31 . uint31) = node
          do (when (= station (- n 1))
               (println dist)
               (return-from main))
             (when (or (null (gethash node dists))
                       (< dist (the uint31 (gethash node dists))))
               (setf (gethash node dists) dist)
               (dolist (node (aref graph station))
                 (let* ((nextstop (car node))
                        (nextcolor (cdr node))
                        (nextdist (if (= nextcolor prevcolor) dist (+ dist 1))))
                   (declare (uint32 nextcolor nextdist))
                   (when (and (null (gethash node dists))
                              (<= nextdist (+ 1 (aref dist-seq nextstop))))
                     (minf (aref dist-seq nextstop) nextdist)
                     (if (= nextcolor prevcolor)
                         (enqueue-front (cons node nextdist) q)
                         (enqueue (cons node nextdist) q)))))))
    (println -1)))

#-swank (main)

Score : 600 points

Problem Statement

Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.

The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.

You can change trains at a station where multiple lines are available.

The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.

Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq 2×10^5

1 \leq p_i \leq N (1 \leq i \leq M)

1 \leq q_i \leq N (1 \leq i \leq M)

1 \leq c_i \leq 10^6 (1 \leq i \leq M)

p_i \neq q_i (1 \leq i \leq M)

Input

The input is given from Standard Input in the following format:

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

Print the minimum required fare. If it is impossible to get to station N by subway, print -1 instead.

Sample Input 1

3 3
1 2 1
2 3 1
3 1 2

Sample Output 1

1

Use company 1's lines: 1 → 2 → 3. The fare is 1 yen.

Sample Input 2

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

Sample Output 2

2

First, use company 1's lines: 1 → 3 → 2 → 5 → 6. Then, use company 5's lines: 6 → 7 → 8. The fare is 2 yen.

Sample Input 3

2 0

Sample Output 3

-1


(let* ((a (read))
    (b (read))
    (c (read))
    (ab (* a b))
    (bc (* b c))
    (ca (* c a))
    (ans 0))
    (if (not (or (zerop (rem a 2)) (zerop (rem b 2)) (zerop (rem c 2))))
        (progn
            (if (<= ab bc)
                (setq ans ab)
                (setq ans bc)
            )
            (if (< ca ans)
                (setq ans ca)
            )
        )
    )
    (format t "~D~%" ans)
)

Score : 200 points

Problem Statement

We have a rectangular parallelepiped of size A×B×C, built with blocks of size 1×1×1. Snuke will paint each of the A×B×C blocks either red or blue, so that:

There is at least one red block and at least one blue block.

The union of all red blocks forms a rectangular parallelepiped.

The union of all blue blocks forms a rectangular parallelepiped.

Snuke wants to minimize the difference between the number of red blocks and the number of blue blocks. Find the minimum possible difference.

Constraints

2≤A,B,C≤10^9

Input

The input is given from Standard Input in the following format:

A B C

Output

Print the minimum possible difference between the number of red blocks and the number of blue blocks.

Sample Input 1

3 3 3

Sample Output 1

9

For example, Snuke can paint the blocks as shown in the diagram below.
There are 9 red blocks and 18 blue blocks, thus the difference is 9.

Sample Input 2

2 2 4

Sample Output 2

0

For example, Snuke can paint the blocks as shown in the diagram below.
There are 8 red blocks and 8 blue blocks, thus the difference is 0.

Sample Input 3

5 3 5

Sample Output 3

15

For example, Snuke can paint the blocks as shown in the diagram below.
There are 45 red blocks and 30 blue blocks, thus the difference is 9.


(let* ((a (read))
    (b (read))
    (c (read))
    (ab (* a b))
    (bc (* b c))
    (ca (* c a))
    (ans 0))
    (if (not (or (zerop (rem a 2)) (zerop (rem b 2)) (zerop (rem c 2))))
        (if (<= ab bc)
            (setq ans ab)
            (setq ans bc)
        )
        (if (<= ca ans)
            (setq ans ca)
        )
    )
    (format t "~D~%" ans)
)


(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 (inline read-schar))
(defun read-schar (&optional (stream *standard-input*))
  (declare #-swank (sb-kernel:ansi-stream stream)
           (inline read-byte))
  #+swank (read-char stream nil #\Newline) ; on SLIME
  #-swank (code-char (read-byte stream nil #.(char-code #\Newline))))

(defmacro with-buffered-stdout (&body body)
  "Buffers all outputs to *STANDARD-OUTPUT* in BODY and flushes them to
*STANDARD-OUTPUT* after BODY has been done (without error). Note that only
BASE-CHAR is allowed."
  (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)))))

(declaim (inline print-matrix))
(defun print-matrix (array &key (separator #\ ) (key #'identity) (row-start 0) row-end (col-start 0) col-end)
  (declare ((array * (* *)) array)
           ((integer 0 #.most-positive-fixnum) row-start col-start))
  (let ((row-end (or row-end (array-dimension array 0)))
        (col-end (or col-end (array-dimension array 1))))
    (declare ((integer 0 #.most-positive-fixnum) row-end col-end))
    (loop for i from row-start below row-end
          do (loop for j from col-start below col-end
                   do (when (and separator (/= j col-start))
                        (princ separator))
                      (write (funcall key (aref array i j))))
          (terpri))))

(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))
         (reds (make-array (list h w) :element-type 'base-char :initial-element #\.))
         (blues (make-array (list h w) :element-type 'base-char :initial-element #\.))
         (plan (make-array (list h w) :element-type 'base-char)))
    (declare (uint16 h w))
    (dotimes (i h)
      (dotimes (j w (read-schar))
        (setf (aref plan i j) (read-schar))))
    (dotimes (i h)
      (setf (aref reds i 0) #\#
            (aref blues i (- w 1)) #\#))
    (dotimes (i h)
      (loop for j from 1 below (- w 1)
            do (setf (aref (if (evenp i) reds blues) i j) #\#)))
    (dotimes (i h)
      (dotimes (j w)
        (when (char= #\# (aref plan i j))
          (setf (aref reds i j) #\#
                (aref blues i j) #\#))))
    (with-buffered-stdout
      (let ((*print-escape* nil))
        (print-matrix reds :separator nil)
        (terpri)
        (print-matrix blues :separator nil)))))

#-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 "5 5
.....
.#.#.
.....
.#.#.
.....
"
    ".....
#####
#....
#####
.....

.###.
.#.#.
.#.#.
.#.#.
.....
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "7 13
.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#.###.###.
.............
"
    ".............
.###########.
.###.###.###.
.###.###.###.
.###.###.###.
.###.###.###.
.............

.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#########.
.............
")))

Score : 700 points

Problem Statement

Snuke and Ciel went to a strange stationery store. Each of them got a transparent graph paper with H rows and W columns.

Snuke painted some of the cells red in his paper. Here, the cells painted red were 4-connected, that is, it was possible to traverse from any red cell to any other red cell, by moving to vertically or horizontally adjacent red cells only.

Ciel painted some of the cells blue in her paper. Here, the cells painted blue were 4-connected.

Afterwards, they precisely overlaid the two sheets in the same direction. Then, the intersection of the red cells and the blue cells appeared purple.

You are given a matrix of letters a_{ij} (1≤i≤H, 1≤j≤W) that describes the positions of the purple cells. If the cell at the i-th row and j-th column is purple, then a_{ij} is #, otherwise a_{ij} is .. Here, it is guaranteed that no outermost cell is purple. That is, if i=1, H or j = 1, W, then a_{ij} is ..

Find a pair of the set of the positions of the red cells and the blue cells that is consistent with the situation described. It can be shown that a solution always exists.

Constraints

3≤H,W≤500

a_{ij} is # or ..

If i=1,H or j=1,W, then a_{ij} is ..

At least one of a_{ij} is #.

Input

The input is given from Standard Input in the following format:

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

Output

Print a pair of the set of the positions of the red cells and the blue cells that is consistent with the situation, as follows:

The first H lines should describe the positions of the red cells.

The following 1 line should be empty.

The following H lines should describe the positions of the blue cells.

The description of the positions of the red or blue cells should follow the format of the description of the positions of the purple cells.

Sample Input 1

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

Sample Output 1

.....
#####
#....
#####
.....

.###.
.#.#.
.#.#.
.#.#.
.....

One possible pair of the set of the positions of the red cells and the blue cells is as follows:

Sample Input 2

7 13
.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#.###.###.
.............

Sample Output 2

.............
.###########.
.###.###.###.
.###.###.###.
.###.###.###.
.###.###.###.
.............

.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#########.
.............

One possible pair of the set of the positions of the red cells and the blue cells is as follows:


(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
(defmacro with-buffered-stdout (&body body)
  "Buffers all outputs to *STANDARD-OUTPUT* in BODY and flushes them to
*STANDARD-OUTPUT* after BODY has been done (without error). Note that only
BASE-CHAR is allowed."
  (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)))))

(declaim (inline print-matrix))
(defun print-matrix (array &key (separator #\ ) (key #'identity) (row-start 0) row-end (col-start 0) col-end)
  (declare ((array * (* *)) array)
           ((integer 0 #.most-positive-fixnum) row-start col-start))
  (let ((row-end (or row-end (array-dimension array 0)))
        (col-end (or col-end (array-dimension array 1))))
    (declare ((integer 0 #.most-positive-fixnum) row-end col-end))
    (loop for i from row-start below row-end
          do (loop for j from col-start below col-end
                   do (when (and separator (/= j col-start))
                        (princ separator))
                      (write (funcall key (aref array i j))))
          (terpri))))

(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))
         (reds (make-array (list h w) :element-type 'base-char :initial-element #\.))
         (blues (make-array (list h w) :element-type 'base-char :initial-element #\.))
         (plan (make-array (list h w) :element-type 'base-char)))
    (declare (uint16 h w))
    (dotimes (i h)
      (let ((line (read-line)))
        (dotimes (j w)
          (setf (aref plan i j) (aref line j)))))
    (dotimes (i h)
      (setf (aref reds i 0) #\#
            (aref blues i (- w 1)) #\#))
    (dotimes (i h)
      (loop for j from 1 below (- w 1)
            do (setf (aref (if (evenp i) reds blues) i j) #\#)))
    (dotimes (i h)
      (dotimes (j w)
        (when (char= #\# (aref plan i j))
          (setf (aref reds i j) #\#
                (aref blues i j) #\#))))
    (with-buffered-stdout
      (let ((*print-escape* nil))
        (print-matrix reds :separator nil)
        (terpri)
        (print-matrix blues :separator nil)))))

#-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 "5 5
.....
.#.#.
.....
.#.#.
.....
"
    ".....
#####
#....
#####
.....

.###.
.#.#.
.#.#.
.#.#.
.....
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "7 13
.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#.###.###.
.............
"
    ".............
.###########.
.###.###.###.
.###.###.###.
.###.###.###.
.###.###.###.
.............

.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#########.
.............
")))


(defvar N (read))
(defvar K (read))

(if (>= K N)
    (princ (* (read) N))
    (princ (+ (* K (read)) (* (- N K) (read)))) )

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

The input is given from Standard Input in the following format:

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


(defun main ()
  (let ((n (read))
        (k (read))
        (x (read))
        (y (read)))
    (format t "~D~%"
            (if (<= n k)
                (* x n)
                (+ (* x k)
                   (* y (- n k)))))))

(main)


  (let ((n (read))
        (k (read))
        (x (read))
        (y (read)))
    (princ (+ (* k x) (* (- n k) y))))
(terpri)


#|
------------------------------------
                Utils
------------------------------------
|#

(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

#-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 define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~a" b)) () '(signed-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~a" b)) () '(unsigned-byte ,b))) bits)))

(define-int-types 2 4 8 16 32 64)

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (term-char #\Space))
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let* ((,buffer (load-time-value (make-string ,buffer-size :element-type 'base-char))))
       (declare (simple-base-string ,buffer)
                (inline read-byte))
       (loop for ,character of-type base-char =
                ,(if (member :swank *features*)
                     `(read-char ,in nil #\Newline) ; on SLIME
                     `(code-char (read-byte ,in nil #.(char-code #\Newline))))
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,term-char))
                     (return (values ,buffer ,idx))))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare (inline read-byte)
           #-swank (sb-kernel:ansi-stream in))
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (read-byte in nil 0))))
    (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) (the (integer 0 #.(floor most-positive-fixnum 10)) (* result 10))))
              (return (if minus (- result) result))))))))

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

(defmacro safe-sort (list test &key (key #'identity))
  `(progn
    (declaim (inline sort sb-impl::stable-sort-list))
    (sort (copy-seq ,list) ,test :key ,key)))

(defmacro read-numbers-to-list (size)
  `(loop repeat ,size collect (read-fixnum)))

(defmacro read-numbers-to-array (size)
  (let ((i (gensym))
        (arr (gensym)))
    `(let ((,arr (make-array ,size
                             :element-type 'fixnum)))
       (declare ((array fixnum 1) ,arr))
       (loop for ,i of-type fixnum below ,size do
            (setf (aref ,arr ,i) (read))
          finally
            (return ,arr)))))

(defmacro read-characters-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym))
        (tmp (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size) :element-type 'character :adjustable nil)))
       (dotimes (,r ,row-size ,board)
         (let ((,tmp (buffered-read-line)))
           (dotimes (,c ,column-size)
             (setf (aref ,board ,r ,c) (char ,tmp ,c))))))))

(defmethod princ-for-each-line ((sequence list))
  (format t "~{~a~&~}" sequence))

(defmethod princ-for-each-line ((sequence vector))
  (loop for i below (length sequence) do
       (princ (aref sequence i))
       (fresh-line)))

(declaim (inline unwrap))
(defun unwrap (list)
  (the string
       (format nil "~{~a~^ ~}" list)))

(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)))))

(defmacro maxf (place cand)
  `(setf ,place (max ,place ,cand)))

(defmacro minf (place cand)
  `(setf ,place (min ,place ,cand)))

(defmacro modf (place &optional (m +mod+))
  `(setf ,place (mod ,place ,m)))

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defun iota (count &optional (start 0) (step 1))
  (loop for i from 0 below count collect (+ start (* i step))))

(defun int->lst (integer)
  (declare ((integer 0) integer))
  (labels ((sub (int &optional (acc nil))
             (declare ((integer 0) int)
                      (list acc))
             (if (zerop int)
                 acc
                 (sub (floor int 10) (cons (rem int 10) acc)))))
    (sub integer)))

(defun lst->int (list)
  (declare (list list))
  (labels ((sub (xs &optional (acc 0))
             (declare (ftype (function (list &optional (integer 0)) (integer 0)) sub))
             (declare (list xs)
                      ((integer 0) acc))
             (if (null xs)
                 acc
                 (sub (rest xs) (+ (* acc 10)
                                   (rem (first xs) 10))))))
    (the fixnum
         (sub list))))

(defun int->str (integer)
  (format nil "~a" integer))

(defun str->int (str)
  (parse-integer str))

(defun char->int (char)
  (declare (character char))
  (- (char-code char) #.(char-code #\0)))

(declaim (inline prime-factorize-to-list))
(defun prime-factorize-to-list (integer)
  (declare ((integer 0) integer))
  (the list
       (if (<= integer 1)
           nil
           (loop
              while (<= (* f f) integer)
              with acc list = nil
              with f integer = 2
              do
                (if (zerop (rem integer f))
                    (progn
                      (push f acc)
                      (setq integer (floor integer f)))
                    (incf f))
              finally
                (when (/= integer 1)
                  (push integer acc))
                (return (reverse acc))))))

(declaim (inline prime-p))
(defun prime-p (integer)
  (declare ((integer 1) integer))
  (if (= integer 1)
      nil
      (loop
         with f = 2
         while (<= (* f f) integer)
         do
           (when (zerop (rem integer f))
             (return nil))
           (incf f)
         finally
           (return t))))

(defconstant +mod+ 1000000007)
;(defconstant +mod+ 998244353)

#|
------------------------------------
                Body
------------------------------------
|#

(defun solve (w)
  (let ((memo (make-array 26)))
    (loop for c in w do
         (incf (aref memo (- (char-code c)
                             #.(char-code #\a)))))
    (if (every #'evenp memo)
        "Yes"
        "No")))

(defun main ()
  (declare #.OPT)
  (let ((w (concatenate 'list (read-line))))
    (princ (solve w))
    (fresh-line)))

#-swank (main)

Score : 200 points

Problem Statement

Let w be a string consisting of lowercase letters.
We will call w beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in w.

You are given the string w. Determine if w is beautiful.

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

The input is given from Standard Input in the following format:

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No


(let* ((str (read-line))
       (ans t))
  (map nil (lambda (n) (if (not (evenp (count n str))) (setf ans nil))) str)
  (if ans (princ "Yes") (princ "No")))


(let* ((n (read))
			 (a (read))
			 (x (make-array n :initial-contents (loop :repeat n :collect (read))))
			 (cache (make-array (expt 51 4) :initial-element nil)))
	(defun s (v k i)
		(cond ((= i n) (if (and (> v 0) (= v (* k a))) 1 0))
					((> v (* a n)) 0)
					(t (let ((key (+ (* v 51 51) (* k 51) i)))
							 (if (aref cache key)
									 (aref cache key)
									 (setf (aref cache key) (+ (s v k (1+ i))
																						 (s (+ v (aref x i)) (1+ k) (1+ i)))))))))
  (format t "~a~%" (s 0 0 0)))

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

The input is given from Standard Input in the following format:

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


(defmacro reads* (syms &body body)
  `(let* (,@(mapcar #'(lambda (sym)
			(if (listp sym) sym `(,sym (read))))
		    syms))
     ,@body))

(reads* (n a (lst (loop repeat n collect (read))) (sum (reduce #'+ lst)))
  (let ((count 0))
    (labels ((back-tracking (depth sum lst ave)
	       (cond ((zerop depth) (when (= sum ave) (incf count)))
		     ((<= ave sum) nil)
		     ((null lst) nil)
		     (t (back-tracking (1- depth)
				       (+ sum (car lst))
				       (cdr lst)
				       ave)
			(back-tracking depth
				       sum
				       (cdr lst)
				       ave)))))
      (loop
	 for lim from a to sum by a
	 finally (princ count)
	 do (back-tracking (/ lim a) 0 lst lim)))))


#|
------------------------------------
                Utils
------------------------------------
|#

(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

#-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 define-int-types (&rest bits)
  `(progn
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "INT~a" b)) () '(signed-byte ,b))) bits)
     ,@(mapcar (lambda (b) `(deftype ,(intern (format nil "UINT~a" b)) () '(unsigned-byte ,b))) bits)))

(define-int-types 2 4 8 16 32 64)

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (term-char #\Space))
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let* ((,buffer (load-time-value (make-string ,buffer-size :element-type 'base-char))))
       (declare (simple-base-string ,buffer)
                (inline read-byte))
       (loop for ,character of-type base-char =
                ,(if (member :swank *features*)
                     `(read-char ,in nil #\Newline) ; on SLIME
                     `(code-char (read-byte ,in nil #.(char-code #\Newline))))
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,term-char))
                     (return (values ,buffer ,idx))))))

(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (declare (inline read-byte)
           #-swank (sb-kernel:ansi-stream in))
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (read-byte in nil 0))))
    (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) (the (integer 0 #.(floor most-positive-fixnum 10)) (* result 10))))
              (return (if minus (- result) result))))))))

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

(defmacro safe-sort (list test &key (key #'identity))
  `(progn
    (declaim (inline sort sb-impl::stable-sort-list))
    (sort (copy-seq ,list) ,test :key ,key)))

(defmacro read-numbers-to-list (size)
  `(loop repeat ,size collect (read-fixnum)))

(defmacro read-numbers-to-array (size)
  (let ((i (gensym))
        (arr (gensym)))
    `(let ((,arr (make-array ,size
                             :element-type 'fixnum)))
       (declare ((array fixnum 1) ,arr))
       (loop for ,i of-type fixnum below ,size do
            (setf (aref ,arr ,i) (read))
          finally
            (return ,arr)))))

(defmacro read-characters-to-board (row-size column-size)
  (let ((board (gensym))
        (r (gensym))
        (c (gensym))
        (tmp (gensym)))
    `(let ((,board (make-array '(,row-size ,column-size) :element-type 'character :adjustable nil)))
       (dotimes (,r ,row-size ,board)
         (let ((,tmp (buffered-read-line)))
           (dotimes (,c ,column-size)
             (setf (aref ,board ,r ,c) (char ,tmp ,c))))))))

(defmethod princ-for-each-line ((sequence list))
  (format t "~{~a~&~}" sequence))

(defmethod princ-for-each-line ((sequence vector))
  (loop for i below (length sequence) do
       (princ (aref sequence i))
       (fresh-line)))

(declaim (inline unwrap))
(defun unwrap (list)
  (the string
       (format nil "~{~a~^ ~}" list)))

(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)))))

(defmacro maxf (place cand)
  `(setf ,place (max ,place ,cand)))

(defmacro minf (place cand)
  `(setf ,place (min ,place ,cand)))

(defmacro modf (place &optional (m +mod+))
  `(setf ,place (mod ,place ,m)))

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defun iota (count &optional (start 0) (step 1))
  (loop for i from 0 below count collect (+ start (* i step))))

(defun int->lst (integer base)
  (declare ((integer 0) integer)
           ((integer 2) base))
  (labels ((sub (int b &optional (acc nil))
             (declare ((integer 0) int)
                      ((integer 2) b)
                      (list acc))
             (if (zerop int)
                 acc
                 (sub (floor int b) b (cons (rem int b) acc)))))
    (sub integer base)))

(defun lst->int (list)
  (declare (list list))
  (labels ((sub (xs &optional (acc 0))
             (declare (ftype (function (list &optional (integer 0)) (integer 0)) sub))
             (declare (list xs)
                      ((integer 0) acc))
             (if (null xs)
                 acc
                 (sub (rest xs) (+ (* acc 10)
                                   (rem (first xs) 10))))))
    (the fixnum
         (sub list))))

(defun int->str (integer)
  (format nil "~a" integer))

(defun str->int (str)
  (parse-integer str))

(defun char->int (char)
  (declare (character char))
  (- (char-code char) #.(char-code #\0)))

(declaim (inline prime-factorize-to-list))
(defun prime-factorize-to-list (integer)
  (declare ((integer 0) integer))
  (the list
       (if (<= integer 1)
           nil
           (loop
              while (<= (* f f) integer)
              with acc list = nil
              with f integer = 2
              do
                (if (zerop (rem integer f))
                    (progn
                      (push f acc)
                      (setq integer (floor integer f)))
                    (incf f))
              finally
                (when (/= integer 1)
                  (push integer acc))
                (return (reverse acc))))))

(declaim (inline prime-p))
(defun prime-p (integer)
  (declare ((integer 1) integer))
  (if (= integer 1)
      nil
      (loop
         with f = 2
         while (<= (* f f) integer)
         do
           (when (zerop (rem integer f))
             (return nil))
           (incf f)
         finally
           (return t))))

(defconstant +mod+ 1000000007)
;(defconstant +mod+ 998244353)

#|
------------------------------------
                Body
------------------------------------
|#

(defparameter *inf* 100000000000)

(defun f (b n &optional (acc 0))
  (if (zerop n)
      acc
      (f b (floor n b) (+ acc (rem n b)))))

(defun solve (n s)
  (if (= s n)
      (1+ n)
      (let ((ans *inf*))
        (loop
           for b from 2 to (isqrt n)
           do
             (when (= (f b n)
                      s)
               (minf ans b)))
        (loop
           for p downfrom (isqrt n) to 1
           do
             (let ((b (1+ (/ (- n s) p))))
               (when (and (integerp b)
                          (= (f b n) s))
                 (minf ans b))))
        (if (/= ans *inf*)
            ans
            -1))))

(defun main ()
  (declare #.OPT)
  (let ((n (read))
        (s (read)))
    (princ (solve n s))
    (fresh-line)))

#-swank (main)

Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

The input is given from Standard Input in the following format:

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


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

;; BEGIN_INSERTED_CONTENTS
;; Below is the variant that returns a sorted list.
(defun enum-divisors (n)
  "Returns the increasing list of all the divisors of N."
  (declare (optimize (speed 3))
           ((integer 1 #.most-positive-fixnum) n))
  (if (= n 1)
      (list 1)
      (let* ((sqrt (isqrt n))
             (result (list 1)))
        (labels ((%enum (i first-half second-half)
                   (declare ((integer 1 #.most-positive-fixnum) i))
                   (cond ((or (< i sqrt)
                              (and (= i sqrt) (/= (* sqrt sqrt) n)))
                          (multiple-value-bind (quot rem) (floor n i)
                            (if (zerop rem)
                                (progn
                                  (setf (cdr first-half) (list i))
                                  (setf second-half (cons quot second-half))
                                  (%enum (1+ i) (cdr first-half) second-half))
                                (%enum (1+ i) first-half second-half))))
                         ((= i sqrt) ; N is a square number here
                          (setf (cdr first-half) (cons i second-half)))
                         (t ; (> i sqrt)
                          (setf (cdr first-half) second-half)))))
          (%enum 2 result (list n))
          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

(declaim (ftype (function * (values uint62 &optional)) calc))
(defun calc (b n)
  (declare (uint62 b n)
           (values uint62))
  (if (< n b)
      n
      (multiple-value-bind (quot rem) (floor n b)
        (+ rem (calc b quot)))))

(defun main ()
  (let* ((n (read))
         (s (read))
         (sqrt (+ 1 (isqrt (- n 1)))))
    (declare (uint62 n s sqrt))
    (println
     (cond ((> s n) -1)
           ((= s n) (+ n 1))
           (t (loop for b from 2 to sqrt
                    when (= s (calc b n))
                    do (return b))
              (let ((divisors (enum-divisors (- n s))))
                (dolist (div divisors -1)
                  (let ((b (+ div 1)))
                    (when (= s (calc b n))
                      (return b))))))))))

#-swank (main)


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

;; BEGIN_INSERTED_CONTENTS
(declaim (inline bisect-left))
(defun bisect-left (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of lower_bound of C++ or bisect_left of Python: Returns the smallest
index (or input) i that fulfills TARGET[i] >= VALUE, where '>=' is the
complement of ORDER. In other words, this function returns the leftmost index at
which VALUE can be inserted with keeping the order. Therefore, TARGET must be
monotonically non-decreasing with respect to ORDER.

This function returns END if VALUE exceeds TARGET[END-1]. Note that the range
[START, END) is half-open. END must be explicitly specified if TARGET is
function. KEY is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((body (accessor &optional declaration)
         `(progn
            (assert (<= start end))
            (if (= start end) end
                (labels
                    ((%bisect-left (left ok)
                       ;; TARGET[OK] >= VALUE always holds (assuming
                       ;; TARGET[END] = +infinity)
                       ,@(list declaration)
                       (let ((mid (ash (+ left ok) -1)))
                         (if (= mid left)
                             (if (funcall order (funcall key (,accessor target left)) value)
                                 ok
                                 left)
                             (if (funcall order (funcall key (,accessor target mid)) value)
                                 (%bisect-left mid ok)
                                 (%bisect-left left mid))))))
                  (%bisect-left start end))))))
    (etypecase target
      (vector
       (let ((end (or end (length target))))
         (body aref (declare ((integer 0 #.most-positive-fixnum) left ok)))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (body funcall)))))

(declaim (inline bisect-right))
(defun bisect-right (target value &key (start 0) end (order #'<) (key #'identity))
  "TARGET := vector | function (taking an integer argument)
ORDER := strict order

Analogue of upper_bound of C++ or bisect_right of Python: Returns the smallest
index (or input) i that fulfills TARGET[i] > VALUE. In other words, this
function returns the rightmost index at which VALUE can be inserted with keeping
the order. TARGET must be monotonically non-decreasing with respect to ORDER.

This function returns END if VALUE >= TARGET[END-1]. Note that the range [START,
END) is half-open. END must be explicitly specified if TARGET is function. KEY
is applied to each element of TARGET before comparison."
  (declare (function key order)
           (integer start)
           ((or null integer) end))
  (macrolet
      ((body (accessor &optional declaration)
         `(progn
            (assert (<= start end))
            (if (= start end)
                end
                (labels
                    ((%bisect-right (left ok)
                       ;; TARGET[OK] > VALUE always holds (assuming
                       ;; TARGET[END] = +infinity)
                       ,@(list declaration)
                       (let ((mid (ash (+ left ok) -1)))
                         (if (= mid left)
                             (if (funcall order value (funcall key (,accessor target left)))
                                 left
                                 ok)
                             (if (funcall order value (funcall key (,accessor target mid)))
                                 (%bisect-right left mid)
                                 (%bisect-right mid ok))))))

                  (%bisect-right start end))))))
    (etypecase target
      (vector
       (when (null end)
         (setf end (length target)))
       (body aref (declare ((integer 0 #.most-positive-fixnum) left ok))))
      (function
       (assert end () "Requires END argument if TARGET is a function.")
       (body funcall)))))

;; Should we do this with UNWIND-PROTECT?
(defmacro with-buffered-stdout (&body body)
  "Buffers all outputs to *STANDARD-OUTPUT* in BODY and flushes them to
*STANDARD-OUTPUT* after BODY has been done (without error). Note that only
BASE-CHAR is allowed."
  (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)))))

(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))))))))

(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 +max-depth+ 17)

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (xs (make-array n :element-type 'uint32))
         (rtable (make-array (list +max-depth+ n) :element-type 'uint32))
         (ltable (make-array (list +max-depth+ n) :element-type 'uint32)))
    (declare (uint32 n))
    (dotimes (i n)
      (setf (aref xs i) (read-fixnum)))
    (let ((l (read))
          (q (read)))
      (declare (uint32 l q))
      (dotimes (i n)
        (let ((rnext (- (bisect-right xs (+ l (aref xs i))) 1)))
          (setf (aref rtable 0 i) rnext))
        (let ((lnext (bisect-left xs (- (aref xs i) l))))
          (setf (aref ltable 0 i) lnext)))
      (loop for depth from 1 below +max-depth+
            do (dotimes (i n)
                 (setf (aref rtable depth i)
                       (aref rtable (- depth 1) (aref rtable (- depth 1) i)))
                 (setf (aref ltable depth i)
                       (aref ltable (- depth 1) (aref ltable (- depth 1) i)))))
      (labels ((query (a b)
                 (if (< a b)
                     (loop with res of-type uint32 = 0
                           for depth from (- +max-depth+ 1) downto 0
                           do (when (< (aref rtable depth a) b)
                                (incf res (ash 1 depth))
                                (setq a (aref rtable depth a)))
                           finally (return (+ res 1)))
                     (loop with res of-type uint32 = 0
                           for depth from (- +max-depth+ 1) downto 0
                           do (when (> (aref ltable depth a) b)
                                (incf res (ash 1 depth))
                                (setq a (aref ltable depth a)))
                           finally (return (+ res 1))))))
        (with-buffered-stdout
          (dotimes (_ q)
            (let ((a (- (read-fixnum) 1))
                  (b (- (read-fixnum) 1)))
              (println (query a b)))))))))

#-swank (main)

Score : 700 points

Problem Statement

N hotels are located on a straight line. The coordinate of the i-th hotel (1 \leq i \leq N) is x_i.

Tak the traveler has the following two personal principles:

He never travels a distance of more than L in a single day.

He never sleeps in the open. That is, he must stay at a hotel at the end of a day.

You are given Q queries. The j-th (1 \leq j \leq Q) query is described by two distinct integers a_j and b_j.
For each query, find the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel following his principles.
It is guaranteed that he can always travel from the a_j-th hotel to the b_j-th hotel, in any given input.

Constraints

2 \leq N \leq 10^5

1 \leq L \leq 10^9

1 \leq Q \leq 10^5

1 \leq x_i < x_2 < ... < x_N \leq 10^9

x_{i+1} - x_i \leq L

1 \leq a_j,b_j \leq N

a_j \neq b_j

N,\,L,\,Q,\,x_i,\,a_j,\,b_j are integers.

Partial Score

200 points will be awarded for passing the test set satisfying N \leq 10^3 and Q \leq 10^3.

Input

The input is given from Standard Input in the following format:

N
x_1 x_2 ... x_N
L
Q
a_1 b_1
a_2 b_2
:
a_Q b_Q

Output

Print Q lines.
The j-th line (1 \leq j \leq Q) should contain the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel.

Sample Input 1

9
1 3 6 13 15 18 19 29 31
10
4
1 8
7 3
6 7
8 5

Sample Output 1

4
2
1
2

For the 1-st query, he can travel from the 1-st hotel to the 8-th hotel in 4 days, as follows:

Day 1: Travel from the 1-st hotel to the 2-nd hotel. The distance traveled is 2.

Day 2: Travel from the 2-nd hotel to the 4-th hotel. The distance traveled is 10.

Day 3: Travel from the 4-th hotel to the 7-th hotel. The distance traveled is 6.

Day 4: Travel from the 7-th hotel to the 8-th hotel. The distance traveled is 10.


(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0)))
  #+swank (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
(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)

(defmacro println (obj &optional (stream '*standard-output*))
  `(let ((*read-default-float-format* 'double-float))
     (prog1 (princ ,obj ,stream) (terpri ,stream))))

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (as (make-array n :element-type 'uint32)))
    (dotimes (i n)
      (setf (aref as i) (parse-integer (read-line) :junk-allowed t)))
    (let ((sum 0))
      (declare (uint32 sum))
      (labels ((skip-zero (i)
                 (cond ((= i n))
                       ((zerop (aref as i)) (skip-zero (1+ i)))
                       (t (traverse i 0))))
               (traverse (i res)
                 (declare (uint32 i res))
                 (cond ((= i n)
                        (incf sum (floor res 2)))
                       ((zerop (aref as i))
                        (incf sum (floor res 2))
                        (skip-zero i))
                       (t (traverse (1+ i) (+ res (aref as i)))))))
        (skip-zero 0))
      (println sum))))

#-swank(main)

Score : 400 points

Problem Statement

Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it.
He has A_i cards with an integer i.

Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1.

Snuke wants to create the maximum number of pairs from his cards, on the condition that no card should be used in multiple pairs. Find the maximum number of pairs that he can create.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

All input values are integers.

Input

The input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum number of pairs that Snuke can create.

Sample Input 1

4
4
0
3
2

Sample Output 1

4

For example, Snuke can create the following four pairs: (1,1),(1,1),(3,4),(3,4).

Sample Input 2

8
2
0
1
6
0
8
2
1

Sample Output 2

9