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

;; BEGIN_INSERTED_CONTENTS
(declaim (inline shuffle!))
(defun shuffle! (vector)
  "Destructively shuffles VECTOR by Fisher-Yates algorithm."
  (declare (vector vector))
  (loop for i from (- (length vector) 1) above 0
        for j = (random (+ i 1))
        do (rotatef (aref vector i) (aref vector j)))
  vector)

;;;
;;; Compact bit vector
;;;

(eval-when (:compile-toplevel :load-toplevel :execute)
  (assert (= sb-vm:n-word-bits 64)))

(defstruct (succinct-bit-vector (:constructor %make-sucbv (storage blocks))
                                (:conc-name sucbv-)
                                (:copier nil))
  (storage nil :type simple-bit-vector)
  (blocks nil :type (simple-array (unsigned-byte 31) (*))))

(defun make-sucbv! (vector)
  "The consequence is undefined when VECTOR is modified after a succinct bit
vector is created."
  (declare #.OPT)
  (check-type vector simple-bit-vector)
  (let* ((vector (if (zerop (mod (length vector) sb-vm:n-word-bits))
                     vector
                     (adjust-array vector
                                   (* sb-vm:n-word-bits (ceiling (length vector) sb-vm:n-word-bits))
                                   :initial-element 0)))
         (len (length vector))
         (block-count (floor len sb-vm:n-word-bits))
         (blocks (make-array (+ 1 block-count)
                             :element-type '(unsigned-byte 31)
                             :initial-element 0))
         (sum 0))
    (declare (simple-bit-vector vector)
             ((integer 0 #.most-positive-fixnum) sum))
    (dotimes (i block-count)
      (setf (aref blocks i) sum)
      (incf sum (logcount (sb-kernel:%vector-raw-bits vector i))))
    (setf (aref blocks block-count) sum)
    (%make-sucbv vector blocks)))

(declaim (inline sucbv-ref))
(defun sucbv-ref (sucbv index)
  (sbit (sucbv-storage sucbv) index))

;; NOTE: No error handling.
(declaim (inline sucbv-rank)
         (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) sucbv-rank))
(defun sucbv-rank (sucbv end)
  "Counts the number of 1's in the range [0, END)."
  (declare #.OPT
           ((integer 0 #.most-positive-fixnum) end))
  (let* ((storage (sucbv-storage sucbv))
         (blocks (sucbv-blocks sucbv))
         (bpos (ash end -6))
         (brem (logand #b111111 end)))
    (+ (aref blocks bpos)
       (logcount (ldb (byte brem 0)
                      (sb-kernel:%vector-raw-bits storage bpos))))))

;;;
;;; Wavelet matrix
;;;

(deftype wavelet-integer () '(integer 0 #.most-positive-fixnum))

(defstruct (wavelet-matrix (:constructor %make-wavelet-matrix
                               (length data zeros
                                &aux (depth (array-dimension data 0))))
                           (:copier nil)
                           (:conc-name wavelet-))
  (depth 0 :type (integer 1 #.most-positive-fixnum))
  (length 0 :type (integer 0 #.most-positive-fixnum))
  (data nil :type (simple-array succinct-bit-vector (*)))
  (zeros nil :type (simple-array (integer 0 #.most-positive-fixnum) (*))))

#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:defknown make-wavelet ((integer 1 #.most-positive-fixnum) vector)
      wavelet-matrix (sb-c:flushable)
    :overwrite-fndb-silently t))

;; TODO: add deftransform for better type derivation
(defun make-wavelet (bit-depth vector)
  (declare ((integer 1 #.most-positive-fixnum) bit-depth))
  (let* ((len (length vector))
         (fitted-len (* sb-vm:n-word-bits (ceiling len sb-vm:n-word-bits)))
         (data (locally (declare #+sbcl (muffle-conditions style-warning))
                 (make-array bit-depth :element-type 'succinct-bit-vector)))
         (zeros (make-array bit-depth :element-type '(integer 0 #.most-positive-fixnum)))
         (tmp (copy-seq vector))
         (lefts (make-array len :element-type (array-element-type vector)))
         (rights (make-array len :element-type (array-element-type vector)))
         (bits (make-array fitted-len :element-type 'bit)))
    (declare ((integer 0 #.most-positive-fixnum) len fitted-len)
             (vector tmp))
    (loop for d from (- bit-depth 1) downto 0
          do (let ((lpos 0)
                   (rpos 0))
               (declare ((integer 0 #.most-positive-fixnum) lpos rpos))
               (dotimes (i len)
                 (let ((bit (logand 1 (ash (aref tmp i) (- d)))))
                   (if (zerop bit)
                       (setf (aref lefts lpos) (aref tmp i)
                             lpos (+ lpos 1))
                       (setf (aref rights rpos) (aref tmp i)
                             rpos (+ rpos 1)))
                   (setf (aref bits i) bit)))
               (setf (aref data d) (make-sucbv! (copy-seq bits))
                     (aref zeros d) lpos)
               (rotatef lefts tmp)
               (replace tmp rights :start1 lpos :end2 rpos)))
    (%make-wavelet-matrix len data zeros)))

(declaim (ftype (function * (values (unsigned-byte 31) &optional)) wavelet-range-count))
(defun wavelet-range-count (wmatrix lo hi &key (start 0) end)
  (declare #.OPT
           ((integer 0 #.most-positive-fixnum) lo hi start)
           ((or null (integer 0 #.most-positive-fixnum)) end))
  (let ((data (wavelet-data wmatrix))
        (zeros (wavelet-zeros wmatrix))
        (end (or end (wavelet-length wmatrix))))
    (labels
        ((dfs (depth start end value)
           (declare ((integer 0 #.most-positive-fixnum) start end value)
                    ((integer -1 #.most-positive-fixnum) depth)
                    (values (integer 0 #.most-positive-fixnum) &optional))
           (cond ((or (= start end)
                      (<= hi value))
                  0)
                 ((= depth -1)
                  (if (< value lo)
                      0
                      (- end start)))
                 (t
                  (let* ((next-value (logior value
                                             (the wavelet-integer (ash 1 depth))))
                         (upper-bound (logior next-value
                                              (- (the wavelet-integer (ash 1 depth)) 1))))
                    (cond ((< upper-bound lo)
                           0)
                          ((and (<= lo value) (< upper-bound hi))
                           (- end start))
                          (t
                           (let ((lcount (sucbv-rank (aref data depth) start))
                                 (rcount (sucbv-rank (aref data depth) end)))
                             (+ (dfs (- depth 1)
                                     (- start lcount)
                                     (- end rcount)
                                     value)
                                (dfs (- depth 1)
                                     (+ (aref zeros depth) lcount)
                                     (+ (aref zeros depth) rcount)
                                     next-value))))))))))
      (dfs (- (wavelet-depth wmatrix) 1) start end 0))))

(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 +inf+ (- (expt 2 11) 1))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (ws-plan (make-array (* 2 n) :element-type 'uint16 :initial-element +inf+))
         (bs-plan (make-array (* 2 n) :element-type 'uint16 :initial-element +inf+))
         (ws-pos (make-array (+ n 1) :element-type 'uint16))
         (bs-pos (make-array (+ n 1) :element-type 'uint16))
         (dp (make-array (list (+ n 1) (+ n 1))
                         :element-type 'uint32
                         :initial-element 0)))
    (declare (uint16 n))
    (dotimes (i (* 2 n))
      (let ((col (read))
            (a (read)))
        (if (eql col 'w)
            (setf (aref ws-plan i) a
                  (aref ws-pos a) i)
            (setf (aref bs-plan i) a
                  (aref bs-pos a) i))))
    (let ((ws-plan (make-wavelet 11 ws-plan))
          (bs-plan (make-wavelet 11 bs-plan))
          (inversions1 (make-array (+ 1 n) :element-type 'uint31))
          (inversions2 (make-array (+ 1 n) :element-type 'uint31)))
      (loop
        for x from 1 to n
        do (setf (aref inversions1 x)
                 (wavelet-range-count ws-plan 0 x :start (+ (aref ws-pos x) 1))))
      (loop
        for y from 1 to n
        do (setf (aref inversions2 y)
                 (wavelet-range-count bs-plan 0 y :start (+ (aref bs-pos y) 1))))
      (loop
        for x from 0 to n
        do (loop
             for y from 0 to n
             unless (= x y 0)
             do (setf (aref dp x y)
                      (min
                       (if (zerop y)
                           #xffffffff
                           (let ((pos (aref bs-pos y)))
                             (+ (aref dp x (- y 1))
                                (wavelet-range-count ws-plan 0 (+ x 1) :start (+ pos 1))
                                (aref inversions2 y))))
                       (if (zerop x)
                           #xffffffff
                           (let ((pos (aref ws-pos x)))
                             (+ (aref dp (- x 1) y)
                                (aref inversions1 x)
                                (wavelet-range-count bs-plan 0 (+ y 1) :start (+ pos 1))))))))))
    (println (aref dp n n))))

#-swank (main)

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

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

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

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

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

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

#+swank
(defun gen-dat ()
  (uiop:with-output-file (out *dat-pathname* :if-exists :supersede)
    (format out "2000~%")
    (let ((vec (make-array 4000)))
      (dotimes (i 2000)
        (setf (aref vec i) (cons 'w (* i 1))
              (aref vec (+ i 2000)) (cons 'b (+ i 1))))
      (shuffle! vec)
      (loop for (col . num) across vec
            do (format out "~A ~A~%" col num)))))

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
B 1
W 2
B 3
W 1
W 3
B 2
"
    "4
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4
B 4
W 4
B 3
W 3
B 2
W 2
B 1
W 1
"
    "18
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "9
W 3
B 1
B 4
W 1
B 5
W 9
W 2
B 6
W 5
B 3
W 8
B 9
W 7
B 2
B 8
W 4
W 6
B 7
"
    "41
")))

Score : 600 points

Problem Statement

There are 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball.
The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by a letter c_i.
c_i = W represents the ball is white; c_i = B represents the ball is black.

Takahashi the human wants to achieve the following objective:

For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the white ball with i written on it is to the left of the white ball with j written on it.

For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the black ball with i written on it is to the left of the black ball with j written on it.

In order to achieve this, he can perform the following operation:

Swap two adjacent balls.

Find the minimum number of operations required to achieve the objective.

Constraints

1 ≤ N ≤ 2000

1 ≤ a_i ≤ N

c_i = W or c_i = B.

If i ≠ j, (a_i,c_i) ≠ (a_j,c_j).

Input

Input is given from Standard Input in the following format:

N
c_1 a_1
c_2 a_2
:
c_{2N} a_{2N}

Output

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

Sample Input 1

3
B 1
W 2
B 3
W 1
W 3
B 2

Sample Output 1

4

The objective can be achieved in four operations, for example, as follows:

Swap the black 3 and white 1.

Swap the white 1 and white 2.

Swap the black 3 and white 3.

Swap the black 3 and black 2.

Sample Input 2

4
B 4
W 4
B 3
W 3
B 2
W 2
B 1
W 1

Sample Output 2

18

Sample Input 3

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

Sample Output 3

41


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

Score: 100 points

Problem Statement

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

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

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

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

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

a b

Output

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

Sample Input 1

5 5

Sample Output 1

5

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

Sample Input 2

2 1

Sample Output 2

1

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

Sample Input 3

11 30

Sample Output 3

11

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

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.


(let ((a (make-array 3))
      (ans 0)
      k)
     (dotimes (x 3)
           (setf (aref a x) (read)))
     (sort a #'<)
     (setf k (read))
     (format t "~A~%" (+ (aref a 0) (aref a 1) (expt (aref a 2) (1+ k)))))

Score: 200 points

Problem Statement

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

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

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

A B C
K

Output

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

Sample Input 1

5 3 11
1

Sample Output 1

30

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

There are three choices:

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

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

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

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

Sample Input 2

3 3 4
2

Sample Output 2

22

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

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

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

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


(let ((a (make-array 3))
      (ans 0)
      k)
     (dotimes (x 3)
           (setf (aref a x) (read)))
     (sort a #'<)
     (setf k (read))
     (format t "~A~%" (+ (aref a 0) (aref a 1) (expt (aref a 2) k))))


#-swank
(unless (member :child-sbcl *features*)
  "I refered from https://competitive12.blogspot.com/2020/03/common-lisp.html thank you!"
  (quit
   :unix-status
   (process-exit-code
    (run-program *runtime-pathname*
                 `("--control-stack-size" "128MB"
                   "--noinform" "--disable-ldb" "--lose-on-corruption" "--end-runtime-options"
                   "--eval" "(push :child-sbcl *features*)"
                   "--script" ,(namestring *load-pathname*))
                 :output t :error t :input t))))
(defmacro dp (name args memo-size &body body)
  (let ((memo (gensym)))
    `(let ((,memo (make-array ,memo-size :initial-element nil)))
       (defun ,name ,args
         (or (aref ,memo ,@args)
             (setf (aref ,memo ,@args)
                   ,@body))))))

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

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

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

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

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

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

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

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

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

(defun range-0-n (n &optional (step 1))
  (loop for i from 0 below n by step collect i))

(defun range-1-n (n &optional (step 1))
  (loop for i from 1 below n by step collect i))

(defun range-a-b (a b &optional (step 1))
  (loop for i from a below b by step collect i))

(defun map-0-n (function n &optional (step 1))
  (mapcar function (range-0-n n step)))

(defun map-1-n (function n &optional (step 1))
  (mapcar function (range-1-n n step)))

(defun map-a-b (function a b &optional (step 1))
  (mapcar function (range-a-b a b step)))

(defun read-string (&optional (stream *standard-input*))
  (labels ((is-empty (x)
             (or (char= x #\space) (char= x #\newline))))
    (loop for char = (read-char stream)
          with result
          when (is-empty char)
            do (return (concatenate 'string (nreverse result)))
          do (push char result))))

(defun merge-sort (lst &optional (compare #'<))
  (let ((turn 0))
    (labels ((merge-list (a b a-length b-length)
               (cond ((zerop a-length) b)
                     ((zerop b-length) a)
                     ((funcall compare (car b) (car a))
                      (incf turn a-length)
                      (cons (car b)
                            (merge-list a (cdr b) a-length (1- b-length))))
                     (t
                      (cons (car a)
                            (merge-list (cdr a) b (1- a-length) b-length)))))
             (f (lst length)
               (if (= length 1)
                   lst
                   (let ((mid (ash length -1)))
                     (merge-list (f (subseq lst 0 mid) mid)
                                 (f (subseq lst mid) (- length mid))
                                 mid
                                 (- length mid))))))
      (values (f lst (length lst)) turn))))

(defun group (lst &optional (test #'eql) (key nil))
  (let ((table (make-hash-table :test test)))
    (mapc (lambda (x)
            (push x (gethash (if key (funcall key x) x) table)))
          lst)
    (loop for value being each hash-value in table
          collect value)))

(defun nearby (&rest args)
  (let ((current (subseq args 0 (ash (length args) -1)))
        (validator (subseq args (ash (length args) -1)))
        (res nil))
    (labels ((check (pos)
               (every (lambda (x y) (and (<= 0 x) (< x y)))
                      pos validator))
             (f (lst)
               (unless lst (return-from f))
               (incf (car lst))
               (when (check lst) (push (copy-list current) res))
               (decf (car lst) 2)
               (when (check lst) (push (copy-list current) res))
               (incf (car lst))
               (f (cdr lst))))
      (f current)
      res)))

(defun main (h w map)
  (every
   (lambda (y)
     (every
      (lambda (x)
        (or (char= (aref map y x) #\.)
            (some (lambda (pos)
                    (char= (aref map (nth 0 pos) (nth 1 pos)) #\#))
                  (nearby y x h w))))
      (range-0-n w)))
   (range-0-n h)))

(let ((h (read))
      (w (read)))
  (format t "~a~%" (if (main
                        h w
                        (make-array
                         (list h w)
                         :initial-contents (collect-times h (read-string))))
                       "Yes"
                       "No")))

Score: 300 points

Problem Statement

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

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

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

Determine if square1001 can achieve his objective.

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

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

Sample Input 2

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

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

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

Sample Output 3

Yes


(defun primep (n)
  (cond
    ((or (= n 2) (= n 3)) t)
    ((or (< n 2) (evenp n)) nil)
    ((loop for i from 3 by 2
           when (> (expt i 2) n)  return t
           when (zerop (mod n i)) return nil))))

(defun prime-sieve (end)
  (let ((array (make-array (1+ end) :initial-element t)) (primes nil))
    (loop for i from 2 to end do
          (when (svref array i) (push i primes)
                (loop for j from (* i 2) to end by i do
                      (setf (svref array j) nil))))
    (coerce (reverse primes) 'vector)))

(defun not-solve-p (a b c d e)
  (primep (+ a b c d e)))

(defun solver ()
  (let* ((n (read))
         (primes (prime-sieve 55555))
         (vec (make-array n)))
    (setf (svref vec 0) 2)
    (loop do
          (loop for i fixnum from 1 below n do
                (setf (svref vec i) (svref primes (random 5637))))
          (loop named inner repeat (expt n 3) do
                (when (not-solve-p (svref vec (random n))
                                   (svref vec (random n))
                                   (svref vec (random n))
                                   (svref vec (random n))
                                   (svref vec (random n)))
                  (return-from inner)))
          (return-from solver (format t "~a~%" vec)))))

(solver)

Score: 400 points

Problem Statement

Print a sequence a_1, a_2, ..., a_N whose length is N that satisfies the following conditions:

a_i (1 \leq i \leq N) is a prime number at most 55 555.

The values of a_1, a_2, ..., a_N are all different.

In every choice of five different integers from a_1, a_2, ..., a_N, the sum of those integers is a composite number.

If there are multiple such sequences, printing any of them is accepted.

Notes

An integer N not less than 2 is called a prime number if it cannot be divided evenly by any integers except 1 and N, and called a composite number otherwise.

Constraints

N is an integer between 5 and 55 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print N numbers a_1, a_2, a_3, ..., a_N in a line, with spaces in between.

Sample Input 1

5

Sample Output 1

3 5 7 11 31

Let us see if this output actually satisfies the conditions.

First, 3, 5, 7, 11 and 31 are all different, and all of them are prime numbers.

The only way to choose five among them is to choose all of them, whose sum is a_1+a_2+a_3+a_4+a_5=57, which is a composite number.

There are also other possible outputs, such as 2 3 5 7 13, 11 13 17 19 31 and 7 11 5 31 3.

Sample Input 2

6

Sample Output 2

2 3 5 7 11 13

2, 3, 5, 7, 11, 13 are all different prime numbers.

2+3+5+7+11=28 is a composite number.

2+3+5+7+13=30 is a composite number.

2+3+5+11+13=34 is a composite number.

2+3+7+11+13=36 is a composite number.

2+5+7+11+13=38 is a composite number.

3+5+7+11+13=39 is a composite number.

Thus, the sequence 2 3 5 7 11 13 satisfies the conditions.

Sample Input 3

8

Sample Output 3

2 5 7 13 19 37 67 79


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

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (as (make-array n :element-type 'int32))
         (cumul (make-array (+ n 1) :element-type 'fixnum :initial-element 0))
         (table (make-hash-table :size n :test #'eq))
         (res 0))
    (declare (uint62 res))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)
            (aref cumul (+ i 1)) (+ (aref cumul i) (aref as i))))
    (dotimes (i (+ n 1))
      (let ((c (aref cumul i)))
        (if (gethash c table)
            (incf res (gethash c table))
            (setf (gethash c table) 0))
        (incf (gethash c table))))
    (println res)))

#-swank (main)

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

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

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

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

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

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

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

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

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

Score : 200 points

Problem Statement

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

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

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

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

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

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

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


(let((h(make-hash-table))(ans 0)(sum 0))
 (setf(gethash 0 h)1)
 (dotimes(i(read))(incf ans(1-(incf(gethash(incf sum(read))h 0)))))
 (princ ans))


;; -*- 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 (inline fast-read-char))
(defun fast-read-char (&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))))

;;;
;;; 2D rolling hash (32-bit)
;;;

(defstruct (rhash2d (:constructor %make-rhash2d (mod1 base1 mod2 base2 table)))
  ;; horizontal
  (mod1 2147483647 :type (unsigned-byte 32))
  (base1 1059428526 :type (unsigned-byte 32))
  ;; vertical
  (mod2 2147483629 :type (unsigned-byte 32))
  (base2 2090066834 :type (unsigned-byte 32))
  (table nil :type (simple-array (unsigned-byte 32) (* *))))

;; This table consists of pairs of primes less than 2^32 and the random
;; primitive roots modulo them larger than 10^9. We randomly choose a pair and
;; adopt the prime as modulus and the primitive root as base.
(declaim ((simple-array (unsigned-byte 32) (100)) *moduli-table* *base-table*))
(defparameter *moduli-table*
  (make-array 100 :element-type '(unsigned-byte 32)
                  :initial-contents '(4294967291 4294967279 4294967231 4294967197 4294967189 4294967161 4294967143
 4294967111 4294967087 4294967029 4294966997 4294966981 4294966943 4294966927
 4294966909 4294966877 4294966829 4294966813 4294966769 4294966667 4294966661
 4294966657 4294966651 4294966639 4294966619 4294966591 4294966583 4294966553
 4294966477 4294966447 4294966441 4294966427 4294966373 4294966367 4294966337
 4294966297 4294966243 4294966237 4294966231 4294966217 4294966187 4294966177
 4294966163 4294966153 4294966129 4294966121 4294966099 4294966087 4294966073
 4294966043 4294966007 4294966001 4294965977 4294965971 4294965967 4294965949
 4294965937 4294965911 4294965887 4294965847 4294965841 4294965839 4294965821
 4294965793 4294965767 4294965757 4294965737 4294965733 4294965721 4294965691
 4294965683 4294965679 4294965673 4294965671 4294965659 4294965641 4294965617
 4294965613 4294965601 4294965581 4294965529 4294965487 4294965461 4294965457
 4294965413 4294965383 4294965361 4294965347 4294965331 4294965313 4294965307
 4294965263 4294965251 4294965229 4294965203 4294965193 4294965161 4294965151
 4294965137 4294965131)))
(defparameter *base-table*
  (make-array 100 :element-type '(unsigned-byte 32)
                  :initial-contents '(2247433164 2139372809 2609807693 2343117402 3096734379 2843084587 3022604264
 3725165355 1310011850 3271696819 3710639434 4215251668 2971116345 1291563131
 2125491020 1561805191 3225016848 4113447491 3038900010 3636011022 2479454799
 1990556577 2661169605 3088947962 1926120766 4105365454 4171519129 2043031086
 1810297004 1391329364 3781496513 3524912702 2014602604 3608350570 2970210993
 4041943368 3843309586 1048071792 2527337250 4207345339 3745845437 3780181639
 1843103547 1471147023 2925746977 2571168523 1911322179 2533579172 2577088289
 3082429185 3636817029 3517246253 2141978180 2042755180 1656982819 2160802626
 3780428251 1987808226 3883058504 1973235694 3022446019 3414211768 2747857698
 1121927034 2368051231 1585372041 2942376489 1760007658 1731546725 3503068146
 3139298718 3516795165 3838735245 3491469147 2711077678 1556341778 2556545397
 1528640652 1183190693 2870857999 3301248018 4114187491 2653041143 1757252280
 3464064684 1655297946 4217483675 2809928527 2757106005 3401026515 2587333052
 1757998238 1398188339 4075136024 2780360736 2566409334 2544620190 1754492744
 2431582005 1565067593)))

(defun %choose-moduli (mod1 mod2 base1 base2 rhash2d)
  "Chooses two appropriate pairs of moduli and bases."
  (declare ((or null (unsigned-byte 32)) mod1 mod2 base1 base2))
  (when rhash2d
    (return-from %choose-moduli
      (values (rhash2d-mod1 rhash2d)
              (rhash2d-mod2 rhash2d)
              (rhash2d-base1 rhash2d)
              (rhash2d-base2 rhash2d))))
  (let* ((rand1 (random (length *moduli-table*)))
         ;; avoid the same modulus
         (rand2 (loop (let ((tmp (random (length *moduli-table*))))
                        (unless (= tmp rand1)
                          (return tmp))))))
    (if mod1
        (progn
          #+sbcl (assert (sb-int:positive-primep mod1))
          (setq base1 (or base1 (+ 1 (random (- mod1 1))))))
        (progn
          (setq mod1 (or mod1 (aref *moduli-table* rand1)))
          (if base1
              (assert (<= 1 base1 (- mod1 1)))
              (setq base1 (aref *base-table* rand1)))))
    (if mod2
        (progn
          #+sbcl (assert (sb-int:positive-primep mod2))
          (setq base2 (or base2 (+ 1 (random (- mod2 1))))))
        (progn
          (setq mod2 (or mod2 (aref *moduli-table* rand2)))
          (if base2
              (assert (<= 1 base2 (- mod2 1)))
              (setq base2 (aref *base-table* rand2))))))
  (values mod1 mod2 base1 base2))

(declaim (inline make-rhash2d))
(defun make-rhash2d (matrix h w &key (key #'identity) mod1 mod2 base1 base2 rhash2d)
  "Returns the table of the hash value of each subrectangle of size H * W on
MATRIX modulo MOD1 and MOD2.

KEY is applied to each element of MATRIX prior to computing the hash value. If
moduli and bases are NIL, this function randomly chooses them. If RHASH2D is
specified, the same moduli and bases as RHASH2D is adopted.

MOD[1|2] := NIL | unsigned 32-bit prime number
BASE1 := NIL | 1 | 2 | ... | MOD1 - 1
BASE2 := NIL | 1 | 2 | ... | MOD2 - 1
KEY := FUNCTION returning FIXNUM
RHASH2D := NIL | RHASH2D"
  (declare (optimize (speed 3))
           ((array * (* *)) matrix)
           ((integer 0 #.most-positive-fixnum) h w)
           ((or null (unsigned-byte 32)) mod1 mod2 base1 base2)
           (function key))
  (multiple-value-bind (mod1 mod2 base1 base2) (%choose-moduli mod1 mod2 base1 base2 rhash2d)
    (declare ((unsigned-byte 32) mod1 mod2 base1 base2))
    (labels ((power (base exp mod)
               (declare ((unsigned-byte 32) base exp mod))
               (let ((res 1))
                 (declare ((unsigned-byte 32) res))
                 (dotimes (i exp res)
                   (setq res (mod (* res base) mod)))))
             (get-cell (i j) ; Returns MATRIX[i][j] as (unsigned-byte 32).
               (declare ((integer 0 #.most-positive-fixnum) i j))
               (the (unsigned-byte 32)
                    (mod (the fixnum (funcall key (aref matrix i j))) mod1))))
      (destructuring-bind (src-h src-w) (array-dimensions matrix)
        (declare ((integer 0 #.most-positive-fixnum) src-h src-w))
        (assert (and (<= h src-h) (<= w src-w)))
        (let* ((table-h (+ 1 (- src-h h)))
               (table-w (+ 1 (- src-w w)))
               (tmp-table (make-array (list src-h table-w)
                                      :element-type '(unsigned-byte 32)))
               (table (make-array (list table-h table-w)
                                  :element-type '(unsigned-byte 32)))
               (coef-row (power base1 w mod1))
               (coef-col (power base2 h mod2)))
          (declare ((integer 0 #.most-positive-fixnum) table-h table-w))
          ;; compute hash values in the horizontal direction
          (dotimes (i src-h)
            (let ((val 0))
              (declare ((unsigned-byte 32) val))
              (dotimes (j w)
                (setq val (mod (+ (* val base1) (get-cell i j)) mod1)))
              (dotimes (j table-w)
                (setf (aref tmp-table i j) val)
                (when (< j (- src-w w))
                  (setq val (mod (+ (mod (* val base1) mod1)
                                    (- mod1 (mod (* coef-row (get-cell i j)) mod1))
                                    (get-cell i (+ j w)))
                                 mod1))))))
          ;; compute hash values in the vertical direction
          (dotimes (j table-w)
            (let ((val 0))
              (declare ((unsigned-byte 32) val))
              (dotimes (i h)
                (setq val (mod (+ (* val base2) (aref tmp-table i j)) mod2)))
              (dotimes (i table-h)
                (setf (aref table i j) val)
                (when (< i (- src-h h))
                  (setq val (mod (+ (mod (* val base2) mod2)
                                    (- mod2 (mod (* coef-col (aref tmp-table i j)) mod2))
                                    (aref tmp-table (the fixnum (+ i h)) j))
                                 mod2))))))
          (%make-rhash2d mod1 base1 mod2 base2 table))))))

(declaim (inline rhash2d-query)
         (ftype (function * (values (unsigned-byte 32) &optional)) rhash2d-query))
(defun rhash2d-query (rhash2d i j)
  "Returns the hash value of the subrectangle whose upper left corner is at
(i, j)."
  (declare ((integer 0 #.most-positive-fixnum) i j))
  (aref (rhash2d-table rhash2d) i j))

(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* ((n (read))
         (plan (make-array (list (* 2 n) (* 2 n)) :element-type 'base-char))
         (transposed (make-array (list (* 2 n) (* 2 n)) :element-type 'base-char)))
    (declare (uint16 n))
    (dotimes (i n)
      (dotimes (j n)
        (let ((c (fast-read-char)))
          (setf (aref plan i j) c
                (aref plan (+ i n) j) c
                (aref plan i (+ j n)) c
                (aref plan (+ i n) (+ j n)) c)))
      (fast-read-char))
    (dotimes (i (* 2 n))
      (dotimes (j (* 2 n))
        (setf (aref transposed j i) (aref plan i j))))
    (let* ((rhash1 (make-rhash2d plan n n :key #'char-code))
           (rhash2 (make-rhash2d transposed n n :key #'char-code :rhash2d rhash1))
           (res 0))
      (declare (uint32 res))
      (dotimes (i n)
        (dotimes (j n)
          (when (= (rhash2d-query rhash1 i j)
                   (rhash2d-query rhash2 j i))
            (incf res))))
      (println res))))

#-swank (main)

Score : 500 points

Problem Statement

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

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

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

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

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

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

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

Constraints

1 \leq N \leq 300

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

2
ab
ca

Sample Output 1

2

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

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

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

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

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

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


(defun func (x)
  (if x
	(+ (if (char= (car x) #\o) 100 0) (func (cdr x))) 0))

(princ (+ 700 (func (concatenate 'list (read-line)))))

Score : 100 points

Problem Statement

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

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

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

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

oxo

Sample Output 1

900

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

Sample Input 2

ooo

Sample Output 2

1000

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

Sample Input 3

xxx

Sample Output 3

700

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


(let* ((n (read))
       (x (read))
       (l (loop repeat n
                collect (read)))
       (least (reduce #'+ l))
       (minimum (apply #'min l)))

  (format t "~A~%"
          (+ (truncate (- x least) minimum) n)))

Score : 200 points

Problem Statement

Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts.

Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition:

For each of the N kinds of doughnuts, make at least one doughnut of that kind.

At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Also, under the constraints of this problem, it is always possible to obey the condition.

Constraints

2 ≤ N ≤ 100

1 ≤ m_i ≤ 1000

m_1 + m_2 + ... + m_N ≤ X ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
m_1
m_2
:
m_N

Output

Print the maximum number of doughnuts that can be made under the condition.

Sample Input 1

3 1000
120
100
140

Sample Output 1

9

She has 1000 grams of Moto and can make three kinds of doughnuts. If she makes one doughnut for each of the three kinds, she consumes 120 + 100 + 140 = 360 grams of Moto. From the 640 grams of Moto that remains here, she can make additional six Doughnuts 2. This is how she can made a total of nine doughnuts, which is the maximum.

Sample Input 2

4 360
90
90
90
90

Sample Output 2

4

Making one doughnut for each of the four kinds consumes all of her Moto.

Sample Input 3

5 3000
150
130
150
130
110

Sample Output 3

26


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

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

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

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

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

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

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

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

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

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

(defun mapa-b (fn a b &optional (step 1))
  (do ((i a (+ i step))
       (result nil))
      ((> i b) (nreverse result))
    (push (funcall fn i) result)))

(defun map0-n (fn n)
  (mapa-b fn 0 n))

(defun map1-n (fn n)
  (mapa-b fn 1 n))

(defun read-string (&optional (stream *standard-input*))
  (labels ((is-empty (x)
             (or (char= x #\space) (char= x #\newline))))
    (loop for char = (read-char stream)
          with result
          when (is-empty char)
            do (return (concatenate 'string (nreverse result)))
          do (push char result))))

(defun main (a b ab x y)
  (labels ((cul-cost (ab-time)
             (+ (* ab-time ab)
                (* (max 0 (- x (ash ab-time -1))) a)
                (* (max 0 (- y (ash ab-time -1))) b))))
    (loop for i from 0 to (* (max x y) 2)
          with res = (expt 10 10)
          do (setf res (min res (cul-cost i)))
          finally (return res))))

(let ((a (read))
      (b (read))
      (ab (read))
      (x (read))
      (y (read)))
  (princ (main a b ab x y)))

Score : 300 points

Problem Statement

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

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

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

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

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

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

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

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

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

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


(let ((a (read))
      (b (read))
      (x (read)))

  (format t "~A~%"
          (if (and (<= a x)
                   (<= x (+ a b)))
            'yes
            'no)))

Score : 100 points

Problem Statement

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

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

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

1 \leq X \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B X

Output

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

Sample Input 1

3 5 4

Sample Output 1

YES

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

Sample Input 2

2 2 6

Sample Output 2

NO

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

Sample Input 3

5 3 2

Sample Output 3

NO

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


(let ((a (read))
      (b (read))
      (x (read)))

  (format t "~A~%"
          (if (and (<= a x)
                   (<= x b))
            'yes
            'no)))


(defun main()
  (let ((a (read)) (b (read)) (x (read)))
	(if (<= a x (+ a b))
	  (princ "YES")
	  (princ "NO"))))

(main)


;;; Utils (quoted from https://competitive12.blogspot.com/2020/03/common-lisp.html)

;; Read fixnum

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

;; fast read-line

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

;;; invoke child process

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

;-------------------
; Write code here
;-------------------

(defun solve (n a)
  (let* ((k (floor n 2))
         (l (sort (copy-seq a) #'<=))
         (cand0 (aref l (1- k)))
         (cand1 (aref l k))
         (res (make-array n)))
    (dotimes (i n)
      (if (<= (aref a i) cand0)
          (setf (aref res i) cand1)
          (setf (aref res i) cand0)))
    res))

(defun main ()
  (let* ((n (read))
         (a (make-array n :initial-contents (read-from-string (concatenate 'string "(" (read-line) ")")))))
    (let ((ans (solve n a)))
      (dotimes (i n)
        (fresh-line)
        (princ (aref ans i))))
    (fresh-line)))

(main)

Score : 300 points

Problem Statement

When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.

You are given N numbers X_1, X_2, ..., X_N, where N is an even number.
For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.

Find B_i for each i = 1, 2, ..., N.

Constraints

2 \leq N \leq 200000

N is even.

1 \leq X_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print N lines.
The i-th line should contain B_i.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of X_2, X_3, X_4 is 4, B_1 = 4.

Since the median of X_1, X_3, X_4 is 3, B_2 = 3.

Since the median of X_1, X_2, X_4 is 3, B_3 = 3.

Since the median of X_1, X_2, X_3 is 4, B_4 = 4.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4


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

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

;; BEGIN_INSERTED_CONTENTS
(in-package :cl-user)

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (as (loop repeat n collect (read)))
         (deg (reduce #'max as))
         (term (reduce (lambda (a b)
                         (labels ((%eval (a)
                                    (min (abs (- a (floor deg 2)))
                                         (abs (- a (ceiling deg 2))))))
                           (if (< (%eval a) (%eval b))
                               a b)))
                       as)))
    (format t "~D ~D~%" deg term)))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5
6 9 4 2 11
"
    "11 6
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
100 0
"
    "100 0
")))

Score : 400 points

Problem Statement

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

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

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

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

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

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

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

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

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

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

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

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

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

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

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

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


(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
(declaim (inline split-ints-into-vector))
(defun split-ints-into-vector (string dest-vector &key (offset 0) (key #'identity))
  (declare (string string)
           (function key)
           ((array * (*)) dest-vector)
           ((integer 0 #.most-positive-fixnum) offset))
  (loop with position = 0
        for idx from offset below (length dest-vector)
        do (setf (values (aref dest-vector idx) position)
                 (parse-integer string :start position :junk-allowed t))
           (setf (aref dest-vector idx) (funcall key (aref dest-vector idx)))
        finally (return dest-vector)))

(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
(declaim ((simple-array double-float (*)) *bernoulli*))
(defparameter *bernoulli*
  #.(coerce
     (mapcar (lambda (x) (float x 1d0))
             '(1 -1/2 1/6 0 -1/30 0 1/42 0 -1/30 0 5/66 0 -691/2730 0 7/6 0 -3617/510 0 43867/798 0 -174611/330 0 854513/138 0 -236364091/2730 0 8553103/6 0 -23749461029/870 0 8615841276005/14332))
     '(simple-array double-float (*))))

(declaim (ftype (function * (values double-float &optional)) log-factorial))
(defun log-factorial (n &optional (terms 2))
  (declare ((integer 0) n)
           ((unsigned-byte 8) terms))
  (let ((n (float n 1d0)))
    (+ #.(log (sqrt (* 2 pi)))
       (* (+ n 0.5d0) (log n))
       (- n)
       (loop for i2 from 2 to (* terms 2) by 2
             sum (/ (aref *bernoulli* i2)
                    (* i2 (- i2 1) (expt n (- i2 1))))
             of-type double-float))))

(defun log-binomial (n k &optional (terms 2))
  (declare ((integer 0) n k))
  (assert (>= n k))
  (if (zerop k)
      1d0
      (- (log-factorial n terms)
         (log-factorial (- n k) terms)
         (log-factorial k terms))))

(defun bisect-nearest (value vector &key (start 0) end)
  (if (<= value (aref vector start))
      (aref vector start)
      (labels ((%bisect (lo hi)
                 (if (<= (- hi lo) 1)
                     (if (or (= (length vector) hi)
                             (>= (- (aref vector hi) value)
                                (- value (aref vector lo))))
                         (aref vector lo)
                         (aref vector hi))
                     (let ((mid (ash (+ hi lo) -1)))
                       (if (<= (aref vector mid) value)
                           (%bisect mid hi)
                           (%bisect lo mid))))))
        (%bisect start (or end (length vector))))))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint31)))
    (split-ints-into-vector (read-line) as)
    (setf as (sort as #'<))
    (loop for i from 1 below n
          with max = -1
          with a1 = -1
          with a2 = -1
          do (let* ((a/2 (bisect-nearest (* 0.5 (aref as i)) as :end i))
                    (b (log-binomial (aref as i) a/2)))
               (when (< max b)
                 (setf max b
                       a1 (aref as i)
                       a2 a/2)))
          finally (format t "~A ~A~%" a1 a2))))

#-swank(main)


(defun fact (n)
  (labels ((rec (n a) (if (= n 0) a (rec (1- n) (* n a)))))
    (rec n 1)))

(defmacro comb (n r) `(/ (fact ,n) (* (fact ,r) (fact (- ,n ,r))))) ;; nCr

(defun solver ()
  (let* ((n (read)) (ai (make-array n :fill-pointer 0))
         sorted-ai m (max 0) (cmax1 0) (cmax2 0) temp answer (pre -1))
    (loop repeat n do
          (vector-push (read) ai))
    (setf sorted-ai (sort (copy-seq ai) #'>))
    (setf max (aref sorted-ai 0))
    (setf m (floor (/ n 2)))
    (loop for i from m below n do
          (setf temp (comb max (aref sorted-ai i)))
          (when (< temp pre) (break))
          (when (> temp cmax1)
            (setf cmax1 temp) (setf answer (aref sorted-ai i))))
    (loop for i from m downto 0 do
          (setf temp (comb max (aref sorted-ai i)))
          (when (< temp pre) (break))
          (when (> temp cmax2)
            (setf cmax2 temp) (setf answer (aref sorted-ai i))))
    (format t "~a ~a~%" max answer)))

(solver)


(defun fact (n)
  (labels ((rec (n a) (if (= n 0) a (rec (1- n) (* n a)))))
    (rec n 1)))

(defmacro comb (n r) `(/ (fact ,n) (* (fact ,r) (fact (- ,n ,r))))) ;; nCr

(defun solver ()
  (let* ((n (read)) (ai (make-array n :fill-pointer 0))
         sorted-ai (max 0) (cmax 0) temp answer)
    (loop repeat n do
          (vector-push (read) ai))
    (setf sorted-ai (sort (copy-seq ai) #'>))
    (setf max (aref sorted-ai 0))
    (loop for i from 1 below n do
          (setf temp (comb max (aref sorted-ai i)))
          (when (> temp cmax)
            (setf cmax temp) (setf answer (aref sorted-ai i))))
    (format t "~a ~a~%" max answer)))

(solver)


(defun input (n)
  (let ((a (make-array n)))
    (loop for i below n do (setf (aref a i) (read)))
    a))

(defparameter p (make-array 15000 :element-type 'integer :initial-element 0))
(setf (aref p 0) 1)
(setf (aref p 1) 1)
(defun fact (n)
  (if (< 0 (aref p n))
    (aref p n)
    (progn (setf (aref p n) (* n (fact (1- n))))
           (aref p n))))

(defun solve (n A)
  (let ((ans nil)
        (f 0))
    (loop for i from 1 below n
          do (loop for j below i
                   for ai = (aref A i) for aj = (aref A j)
                   for x = (/ (fact ai) (fact aj) (fact (- ai aj)))
                   when (> x f)
                   do (progn (setq ans (cons (aref a i) (aref a j)))
                             (setq f x))))
    ans))

(let* ((n (read))
      (a (sort (input n) #'<))
      (e (solve n a)))
  (format t "~A ~A~%" (car e) (cdr e)))


(let ((s (read-line)))
     (if (every (lambda (c)
                   	(= (count c s)
                       1))
                "abc")
         (princ "Yes")
         (princ "No")))

Score : 100 points

Problem Statement

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

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

bac

Sample Output 1

Yes

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

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


(let((h(make-hash-table)))(mapcar #'(lambda(a)(incf(gethash a h 0)))(coerce(read-line)'list))(princ(if(and(=(gethash #\a h)1)(=(gethash #\b h)1)(=(gethash #\c h)1))"Yes""No")))


(defun main ()
  (let ((a (read))
        (b (read))
        (k (read)))
    (loop for i from a upto b
          do (if (or (< i (+ a k)) (< (- b k) i)) (format t "~A~%" i)))))

(main)

Score : 200 points

Problem Statement

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

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

Constraints

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

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

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

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

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

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

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

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

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


(defun solve(a b c)
    (let ((r (- c a))
	  (s (- c b)))
      (cond
	((and (evenp r) (evenp s)) (truncate (+ r s) 2))
	((and (evenp r) (oddp s)) (+ 2 (truncate (+ r s) 2)))
	((and (oddp r) (evenp s)) (+ 2 (truncate (+ r s) 2)))
	(t (truncate (+ r s) 2)))))

(defun main()
    (let ((l (sort (read-from-string (concatenate 'string "(" (read-line) ")")) #'<=)))
      (destructuring-bind (a b c) l
	(princ (solve a b c))
	(fresh-line))))

(main)

Score : 300 points

Problem Statement

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

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

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

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

Constraints

0 \leq A,B,C \leq 50

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

2 5 4

Sample Output 1

2

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

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

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

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23


(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
;;;
;;; Memoization macro
;;;

;;
;; Basic usage:
;;
;; (with-cache (:hash-table :test #'equal :key #'cons)
;;   (defun add (a b)
;;     (+ a b)))
;; This function caches the returned values for already passed combinations of
;; arguments. In this case ADD stores the key (CONS A B) and the returned value
;; to a hash-table when (ADD A B) is evaluated for the first time. ADD returns
;; the stored value when it is called with the same arguments (w.r.t. EQUAL)
;; again.
;;
;; The storage for cache can be hash-table or array. Let's see an example for
;; array:
;; (with-cache (:array (10 20 30) :initial-element -1 :element-type 'fixnum)
;;   (defun foo (a b c) ... ))
;; This form stores the value of FOO in an array created by (make-array (list 10
;; 20 30) :initial-element -1 :element-type 'fixnum). Note that INITIAL-ELEMENT
;; must always be given here as it is used as the flag expressing `not yet
;; stored'. (Therefore INITIAL-ELEMENT should be a value FOO never takes.)
;;
;; If you want to ignore some arguments, you can put `*' in dimensions:
;; (with-cache (:array (10 10 * 10) :initial-element -1)
;;   (defun foo (a b c d) ...)) ; then C is ignored when querying or storing cache
;;
;; Available definition forms in WITH-CACHE are DEFUN, LABELS, FLET, and
;; SB-INT:NAMED-LET.
;;
;; You can trace the memoized function by :TRACE option:
;; (with-cache (:array (10 10) :initial-element -1 :trace t)
;;   (defun foo (x y) ...))
;; Then FOO is traced as with CL:TRACE.
;;

;; TODO & NOTE: Currently a memoized function is not enclosed with a block of
;; the function name.

;; FIXME: *RECURSION-DEPTH* should be included within the macro.
(declaim (type (integer 0 #.most-positive-fixnum) *recursion-depth*))
(defparameter *recursion-depth* 0)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defun %enclose-with-trace (fname args form)
    (let ((value (gensym)))
      `(progn
         (format t "~&~A~A: (~A ~{~A~^ ~}) =>"
                 (make-string *recursion-depth*
                              :element-type 'base-char
                              :initial-element #\ )
                 *recursion-depth*
                 ',fname
                 (list ,@args))
         (let ((,value (let ((*recursion-depth* (1+ *recursion-depth*)))
                         ,form)))
           (format t "~&~A~A: (~A ~{~A~^ ~}) => ~A"
                   (make-string *recursion-depth*
                                :element-type 'base-char
                                :initial-element #\ )
                   *recursion-depth*
                   ',fname
                   (list ,@args)
                   ,value)
           ,value))))

  (defun %extract-declarations (body)
    (remove-if-not (lambda (form) (and (consp form) (eql 'declare (car form))))
                   body))

  (defun %parse-cache-form (cache-specifier)
    (let ((cache-type (car cache-specifier))
          (cache-attribs (cdr cache-specifier)))
      (assert (member cache-type '(:hash-table :array)))
      (let* ((dims-with-* (when (eql cache-type :array) (first cache-attribs)))
             (dims (remove '* dims-with-*))
             (rank (length dims))
             (rest-attribs (ecase cache-type
                             (:hash-table cache-attribs)
                             (:array (cdr cache-attribs))))
             (key (prog1 (getf rest-attribs :key) (remf rest-attribs :key)))
             (trace-p (prog1 (getf rest-attribs :trace) (remf rest-attribs :trace)))
             (cache-form (case cache-type
                           (:hash-table `(make-hash-table ,@rest-attribs))
                           (:array `(make-array (list ,@dims) ,@rest-attribs))))
             (initial-element (when (eql cache-type :array)
                                (assert (member :initial-element rest-attribs))
                                (getf rest-attribs :initial-element))))
        (let ((cache (gensym "CACHE"))
              (value (gensym))
	      (present-p (gensym))
              (name-alias (gensym))
	      (args-lst (gensym))
              (indices (loop repeat rank collect (gensym))))
          (labels
              ((make-cache-querier (cache-type name args)
                 (let ((res (case cache-type
                              (:hash-table
                               `(let ((,args-lst (funcall ,(or key '#'list) ,@args)))
                                  (multiple-value-bind (,value ,present-p)
                                      (gethash ,args-lst ,cache)
                                    (if ,present-p
                                        ,value
                                        (setf (gethash ,args-lst ,cache)
                                              (,name-alias ,@args))))))
                              (:array
                               (assert (= (length args) (length dims-with-*)))
                               (let ((memoized-args (loop for dimension in dims-with-*
                                                          for arg in args
                                                          unless (eql dimension '*)
                                                          collect arg)))
                                 (if key
                                     `(multiple-value-bind ,indices
                                          (funcall ,key ,@memoized-args)
                                        (let ((,value (aref ,cache ,@indices)))
                                          (if (eql ,initial-element ,value)
                                              (setf (aref ,cache ,@indices)
                                                    (,name-alias ,@args))
                                              ,value)))
                                     `(let ((,value (aref ,cache ,@memoized-args)))
                                        (if (eql ,initial-element ,value)
                                            (setf (aref ,cache ,@memoized-args)
                                                  (,name-alias ,@args))
                                            ,value))))))))
                   (if trace-p
                       (%enclose-with-trace name args res)
                       res)))
               (make-reset-form (cache-type)
                 (case cache-type
                   (:hash-table `(setf ,cache (make-hash-table ,@rest-attribs)))
                   (:array `(prog1 nil
                              ;; TODO: portable fill
                              (fill (array-storage-vector ,cache) ,initial-element)))))
               (make-reset-name (name)
                 (intern (format nil "RESET-~A" (symbol-name name)))))
            (values cache cache-form cache-type name-alias
                    #'make-reset-name
                    #'make-reset-form
                    #'make-cache-querier)))))))

(defmacro with-cache ((cache-type &rest cache-attribs) def-form)
  "CACHE-TYPE := :HASH-TABLE | :ARRAY.
DEF-FORM := definition form with DEFUN, LABELS, FLET, or SB-INT:NAMED-LET."
  (multiple-value-bind (cache-symbol cache-form cache-type name-alias
                        make-reset-name make-reset-form
                        make-cache-querier)
      (%parse-cache-form (cons cache-type cache-attribs))
    (ecase (car def-form)
      ((defun)
       (destructuring-bind (_ name args &body body) def-form
         (declare (ignore _))
         `(let ((,cache-symbol ,cache-form))
            (defun ,(funcall make-reset-name name) ()
              ,(funcall make-reset-form cache-type))
            (defun ,name ,args
              ,@(%extract-declarations body)
              (labels ((,name-alias ,args ,@body))
                (declare (inline ,name-alias))
                ,(funcall make-cache-querier cache-type name args))))))
      ((labels flet)
       (destructuring-bind (_ definitions &body labels-body) def-form
         (declare (ignore _))
         (destructuring-bind (name args &body body) (car definitions)
           `(let ((,cache-symbol ,cache-form))
              (,(car def-form)
               ((,(funcall make-reset-name name) ()
                 ,(funcall make-reset-form cache-type))
                (,name ,args
                       ,@(%extract-declarations body)
                       (labels ((,name-alias ,args ,@body))
                         (declare (inline ,name-alias))
                         ,(funcall make-cache-querier cache-type name args)))
                ,@(cdr definitions))
               (declare (ignorable #',(funcall make-reset-name name)))
               ,@labels-body)))))
      ((nlet #+sbcl sb-int:named-let)
       (destructuring-bind (_ name bindings &body body) def-form
         (declare (ignore _))
         `(let ((,cache-symbol ,cache-form))
            (,(car def-form) ,name ,bindings
             ,@(%extract-declarations body)
             ,(let ((args (mapcar (lambda (x) (if (atom x) x (car x))) bindings)))
                `(labels ((,name-alias ,args ,@body))
                   (declare (inline ,name-alias))
                   ,(funcall make-cache-querier cache-type name args))))))))))

(defmacro with-caches (cache-specs def-form)
  "DEF-FORM := definition form by LABELS or FLET.

 (with-caches (cache-spec1 cache-spec2)
   (labels ((f (x) ...) (g (y) ...))))
is equivalent to the line up of
 (with-cache cache-spec1 (labels ((f (x) ...))))
and
 (with-cache cache-spec2 (labels ((g (y) ...))))

This macro will be useful to do mutual recursion between memoized local
functions."
  (assert (member (car def-form) '(labels flet)))
  (let (cache-symbol-list cache-form-list cache-type-list name-alias-list make-reset-name-list make-reset-form-list make-cache-querier-list)
    (dolist (cache-spec (reverse cache-specs))
      (multiple-value-bind (cache-symbol cache-form cache-type name-alias
                            make-reset-name make-reset-form make-cache-querier)
          (%parse-cache-form cache-spec)
        (push cache-symbol cache-symbol-list)
        (push cache-form cache-form-list)
        (push cache-type cache-type-list)
        (push name-alias name-alias-list)
        (push make-reset-name make-reset-name-list)
        (push make-reset-form make-reset-form-list)
        (push make-cache-querier make-cache-querier-list)))
    (labels ((def-name (def) (first def))
             (def-args (def) (second def))
             (def-body (def) (cddr def)))
      (destructuring-bind (_ definitions &body labels-body) def-form
        (declare (ignore _))
        `(let ,(loop for cache-symbol in cache-symbol-list
                     for cache-form in cache-form-list
                     collect `(,cache-symbol ,cache-form))
           (,(car def-form)
            (,@(loop for def in definitions
                     for cache-type in cache-type-list
                     for make-reset-name in make-reset-name-list
                     for make-reset-form in make-reset-form-list
                     collect `(,(funcall make-reset-name (def-name def)) ()
                               ,(funcall make-reset-form cache-type)))
             ,@(loop for def in definitions
                     for cache-type in cache-type-list
                     for name-alias in name-alias-list
                     for make-cache-querier in make-cache-querier-list
                     collect `(,(def-name def) ,(def-args def)
                               ,@(%extract-declarations (def-body def))
                               (labels ((,name-alias ,(def-args def) ,@(def-body def)))
                                 (declare (inline ,name-alias))
                                 ,(funcall make-cache-querier cache-type (def-name def) (def-args def))))))
            (declare (ignorable ,@(loop for def in definitions
                                        for make-reset-name in make-reset-name-list
                                        collect `#',(funcall make-reset-name
                                                             (def-name def)))))
            ,@labels-body))))))

(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 proc1 (n as bs table)
;;   (let ((flags (make-array n :element-type ')))))

;; (defun test (size)
;;   (let ((mat (make-array (list (+ size 1) (+ size 1))
;;                          :element-type 'uint8
;;                          :initial-element #xff)))
;;     (loop for y from 1 to size
;;           do (loop for x from (+ 1 (* 2 x)) to size
;;                    do (let ((y y))
;;                         (dotimes (i #x100)
;;                           (when (= y x))))))))

(defun preprocess ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint8))
         (bs (make-array n :element-type 'uint8)))
    (dotimes (i n)
      (setf (aref as i) (read)))
    (dotimes (i n)
      (setf (aref bs i) (read)))
    (loop named outer
          do (dotimes (i (length as) (return-from outer))
               (when (= (aref as i) (aref bs i))
                 (setq as (concatenate '(simple-array uint8 (*))
                                       (subseq as 0 i) (subseq as (+ i 1))))
                 (setq bs (concatenate '(simple-array uint8 (*))
                                       (subseq bs 0 i) (subseq bs (+ i 1))))
                 (return))))
    (values (length as) as bs)))

(defun calc-min (from to)
  (when (= from to)
    (return-from calc-min 0))
  (when (<= from (* 2 to))
    (return-from calc-min #xff))
  (let ((res 0))
    (loop
      ;; (dbg from to)
      (when (= from to)
        (return res))
      (loop for x from 1 to 100
            for rem = (mod from x)
            do (when (or (= rem to) (> rem (* 2 to)))
                 (setq from rem)
                 (setq res (max res x))
                 (return))))))

(defun main ()
  (multiple-value-bind (n as bs) (preprocess)
    (loop for a across as
          for b across bs
          unless (>= a (+ 1 (* 2 b)))
          do (println -1)
             (return-from main))
    (with-cache (:hash-table :test #'equal)
      (labels ((dp (x y bits)
                 (dbg x y bits)
                 (labels ((dfs (x pos)
                            (cond ((= x y) 0)
                                  ((<= x (* 2 y)) #xff)
                                  ((= pos 0)
                                   (calc-min x y))
                                  ((and (<= pos x) (logbitp pos bits))
                                   (min (dfs (mod x pos) (- pos 1))
                                        (dfs x (- pos 1))))
                                  (t
                                   (dfs x (- pos 1))))))
                   (dfs x 26))))
        (let ((bits 0))
          (loop repeat 26
                do (let ((x (loop for a across as
                                  for b across bs
                                  maximize (dp a b bits))))
                     (when (zerop x)
                       (return))
                     (setf (ldb (byte 1 x) bits) 1)))
          (println bits))))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
19 10 14
0 3 4
"
    "160
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
19 15 14
0 0 0
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
8 13
5 13
"
    "-1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4
2 0 1 8
2 0 1 8
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "1
50
13
"
    "137438953472
")))

Score : 700 points

Problem Statement

Aoki is playing with a sequence of numbers a_{1}, a_{2}, ..., a_{N}. Every second, he performs the following operation :

Choose a positive integer k. For each element of the sequence v, Aoki may choose to replace v with its remainder when divided by k, or do nothing with v. The cost of this operation is 2^{k} (regardless of how many elements he changes).

Aoki wants to turn the sequence into b_{1}, b_{2}, ..., b_{N} (the order of the elements is important). Determine if it is possible for Aoki to perform this task and if yes, find the minimum cost required.

Constraints

1 \leq N \leq 50

0 \leq a_{i}, b_{i} \leq 50

All values in the input are integers.

Input

Input is given from Standard Input in the following format:

N
a_{1} a_{2} ... a_{N}
b_{1} b_{2} ... b_{N}

Output

Print the minimum cost required to turn the original sequence into b_{1}, b_{2}, ..., b_{N}. If the task is impossible, output -1 instead.

Sample Input 1

3
19 10 14
0 3 4

Sample Output 1

160

Here's a possible sequence of operations :

Choose k = 7. Replace 19 with 5, 10 with 3 and do nothing to 14. The sequence is now 5, 3, 14.

Choose k = 5. Replace 5 with 0, do nothing to 3 and replace 14 with 4. The sequence is now 0, 3, 4.

The total cost is 2^{7} + 2^{5} = 160.

Sample Input 2

3
19 15 14
0 0 0

Sample Output 2

2

Aoki can just choose k = 1 and turn everything into 0. The cost is 2^{1} = 2.

Sample Input 3

2
8 13
5 13

Sample Output 3

-1

The task is impossible because we can never turn 8 into 5 using the given operation.

Sample Input 4

4
2 0 1 8
2 0 1 8

Sample Output 4

0

Aoki doesn't need to do anything here. The cost is 0.

Sample Input 5

1
50
13

Sample Output 5

137438953472

Beware of overflow issues.


(defun in-and-min ()
  (min (read) (read)))

(princ (+ (in-and-min) (in-and-min)))

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152