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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; 1-dimensional binary indexed tree
;;;

;; TODO: multidimensional BIT

(defmacro define-bitree (name &key (operator '#'+) (identity 0) sum-type (order '#'>))
  "OPERATOR := binary operator (on a commutative monoid)
IDENTITY := object (identity element of the monoid)
ORDER := nil | strict comparison operator on the monoid
SUM-TYPE := nil | type specifier

Defines no structure; BIT is just a vector. This macro defines the three
function: <NAME>-UPDATE!, <NAME>-SUM and COERCE-TO-<NAME>!. If ORDER is
specified, this macro defines the bisection function <NAME>-BISECT-LEFT in
addition. (Note that the -BISECT-LEFT function works only when the sequence of
prefix sums (VECTOR[0], VECTOR[0]+VECTOR[1], ...) is monotonous.)

SUM-TYPE is used only for the type declaration: each sum
VECTOR[i]+VECTOR[i+1]...+VECTOR[i+k] is declared to be this type. (The
element-type of vector itself doesn't need to be SUM-TYPE.)"
  (let* ((name (string name))
         (fname-update (intern (format nil "~A-UPDATE!" name)))
         (fname-sum (intern (format nil "~A-SUM" name)))
         (fname-coerce (intern (format nil "COERCE-TO-~A!" name)))
         (fname-bisect-left (intern (format nil "~A-BISECT-LEFT" name)))
         (fname-bisect-right (intern (format nil "~A-BISECT-RIGHT" name))))
    `(progn
       (declaim (inline ,fname-update))
       (defun ,fname-update (bitree index delta)
         "Destructively increments the vector: vector[INDEX] = vector[INDEX] +
DELTA"
         (let ((len (length bitree)))
           (do ((i index (logior i (+ i 1))))
               ((>= i len) bitree)
             (declare ((integer 0 #.most-positive-fixnum) i))
             (setf (aref bitree i)
                   (funcall ,operator (aref bitree i) delta)))))

       (declaim (inline ,fname-sum))
       (defun ,fname-sum (bitree end)
         "Returns the sum of the prefix: vector[0] + ... + vector[END-1]."
         (declare ((integer 0 #.most-positive-fixnum) end))
         (let ((res ,identity))
           ,@(when sum-type `((declare (type ,sum-type res))))
           (do ((i (- end 1) (- (logand i (+ i 1)) 1)))
               ((< i 0) res)
             (declare ((integer -1 #.most-positive-fixnum) i))
             (setf res (funcall ,operator res (aref bitree i))))))

       (declaim (inline ,fname-coerce))
       (defun ,fname-coerce (vector)
         "Destructively constructs BIT from VECTOR."
         (loop with len = (length vector)
               for i below len
               for dest-i = (logior i (+ i 1))
               when (< dest-i len)
               do (setf (aref vector dest-i)
                        (funcall ,operator (aref vector dest-i) (aref vector i)))
               finally (return vector)))

       ,@(when order
           `((declaim (inline ,fname-bisect-left))
             (defun ,fname-bisect-left (bitree value)
               "Returns the smallest index that fulfills VECTOR[0]+ ... +
VECTOR[index] >= VALUE. Returns the length of VECTOR if VECTOR[0]+
... +VECTOR[length-1] < VALUE."
               (declare (vector bitree))
               (if (not (funcall ,order value ,identity))
                   0
                   (let ((len (length bitree))
                         (index+1 0)
                         (cumul ,identity))
                     (declare ((integer 0 #.most-positive-fixnum) index+1)
                              ,@(when sum-type
                                  `((type ,sum-type cumul))))
                     (do ((delta (ash 1 (- (integer-length len) 1))
                                 (ash delta -1)))
                         ((zerop delta) index+1)
                       (declare ((integer 0 #.most-positive-fixnum) delta))
                       (let ((next-index (+ index+1 delta -1)))
                         (when (< next-index len)
                           (let ((next-cumul (funcall ,operator cumul (aref bitree next-index))))
                             ,@(when sum-type
                                 `((declare (type ,sum-type next-cumul))))
                             (when (funcall ,order value next-cumul)
                               (setf cumul next-cumul)
                               (incf index+1 delta)))))))))
             (declaim (inline ,fname-bisect-right))
             (defun ,fname-bisect-right (bitree value)
               "Returns the smallest index that fulfills VECTOR[0]+ ... +
VECTOR[index] > VALUE. Returns the length of VECTOR if VECTOR[0]+
... +VECTOR[length-1] <= VALUE."
               (declare (vector bitree))
               (if (funcall ,order ,identity value)
                   0
                   (let ((len (length bitree))
                         (index+1 0)
                         (cumul ,identity))
                     (declare ((integer 0 #.most-positive-fixnum) index+1)
                              ,@(when sum-type
                                  `((type ,sum-type cumul))))
                     (do ((delta (ash 1 (- (integer-length len) 1))
                                 (ash delta -1)))
                         ((zerop delta) index+1)
                       (declare ((integer 0 #.most-positive-fixnum) delta))
                       (let ((next-index (+ index+1 delta -1)))
                         (when (< next-index len)
                           (let ((next-cumul (funcall ,operator cumul (aref bitree next-index))))
                             ,@(when sum-type
                                 `((declare (type ,sum-type next-cumul))))
                             (unless (funcall ,order next-cumul value)
                               (setf cumul next-cumul)
                               (incf index+1 delta))))))))))))))

(define-bitree bitree
  :operator #'+
  :identity 0
  :sum-type fixnum)

;; Scheme-style named let
(defmacro nlet (name args &body body)
  (labels ((ensure-list (x) (if (listp x) x (list x))))
    (let ((args (mapcar #'ensure-list args)))
      `(labels ((,name ,(mapcar #'car args) ,@body))
         (,name ,@(mapcar #'cadr args))))))

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun feasible-p (as x)
  (declare #.OPT
           ((simple-array uint32 (*)) as)
           (uint32 x))
  (let* ((n (length as))
         (cumul (make-array (+ n 1) :element-type 'int32 :initial-element 0))
         (dp (make-array 200001 :element-type 'uint32 :initial-element 0))
         (res 0)
         (threshold (ceiling (* n (+ n 1)) 4)))
    (declare (fixnum res threshold))
    (dotimes (i n)
      (setf (aref cumul (+ i 1))
            (+ (aref cumul i) (if (>= (aref as i) x) 1 -1))))
    (loop for r from 0 to n
          for sr = (aref cumul r)
          do (incf res (bitree-sum dp (+ 100001 sr)))
             (bitree-update! dp (+ 100000 sr) 1))
    (>= res threshold)))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint32)))
    (dotimes (i n) (setf (aref as i) (read-fixnum)))
    (nlet bisect ((ok 1) (ng 1000000001))
      (if (<= (- ng ok) 1)
          (println ok)
          (let ((mid (ash (+ ok ng) -1)))
            (if (feasible-p as mid)
                (bisect mid ng)
                (bisect ok mid)))))))

#-swank(main)

Score : 700 points

Problem Statement

We will define the median of a sequence b of length M, as follows:

Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.

For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.

Snuke comes up with the following problem.

You are given a sequence a of length N.
For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a.
We will list m_{l, r} for all pairs (l, r) to create a new sequence m.
Find the median of m.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the median of m.

Sample Input 1

3
10 30 20

Sample Output 1

30

The median of each contiguous subsequence of a is as follows:

The median of (10) is 10.

The median of (30) is 30.

The median of (20) is 20.

The median of (10, 30) is 30.

The median of (30, 20) is 30.

The median of (10, 30, 20) is 20.

Thus, m = (10, 30, 20, 30, 30, 20) and the median of m is 30.

Sample Input 2

1
10

Sample Output 2

10

Sample Input 3

10
5 9 5 9 8 9 3 5 4 3

Sample Output 3

8


(defvar *N* (read))

(defun split-string (s d)
  (let ((l (concatenate 'list s))
        (r (list nil))
        (tmp (list nil)))
    (dolist (n l)
      (if (eql n d)
          (progn
            (push (parse-integer (concatenate 'string (cdr (reverse tmp)))) r)
            (setq tmp (list nil)))
          (push n tmp)))
    (let ((check (parse-integer (concatenate 'string (cdr (reverse tmp))) :junk-allowed t)))
      (unless (null check)
        (push check r)))
    (cdr (reverse r))))

(defun get-median (l)
  (let* ((size (length l))
         (check (round (/ (float size) 2))))
    (nth check l)))

(defun main ()
  (let ((s (read-line)))
    (let* ((l (split-string s #\Space))
           (result (reverse l)))
      (dotimes (n *N*)
        (let ((right (+ n 1)))
          (if (/= right *N*)
              (progn
                (let* ((tmp (list (nth n l) (nth right l)))
                       (sorted (sort tmp #'<)))
                  (push (cadr sorted) result)))
              (push (get-median (sort l #'<)) result))))
      (setq result (sort (reverse result) #'<))
      (format t "~A~%" (get-median result)))))

(main)

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

Submitted source-code file size, in bytes.

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

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


(in-package :cl-user)
(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 (set-dispatch-macro-character #\# #\> #'cl-debug-print:debug-print-reader)

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

(defconstant +mod+ 1000000007)

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

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

;;;
;;; Body
;;;

(defun main ()
  (let* ((a (read))
         (b (read)))
    (println (+ (* a b) (- a) (- b) 1))))

#-swank (main)

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

#+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* (or out (make-string-output-stream)))
         (res (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))))))
    (if out res (get-output-stream-string *standard-output*))))

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

#-swank
(eval-when (:compile-toplevel)
  (when (and (boundp 'sb-c::*compiler-warning-count*)
             (> sb-c::*compiler-warning-count* 0))
    (sb-ext:quit :unix-status 1)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (5am:is
   (equal "1
"
          (run "2 2
" nil)))
  (5am:is
   (equal "24
"
          (run "5 7
" nil))))

Score: 100 points

Problem Statement

There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)

What is the area of this yard excluding the roads? Find it.

Note

It can be proved that the positions of the roads do not affect the area.

Constraints

A is an integer between 2 and 100 (inclusive).

B is an integer between 2 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

A B

Output

Print the area of this yard excluding the roads (in square yards).

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


(let ((n (read))
    (ans 0)
    (yakusu 0))

    (loop for i from 1 to n by 2 do
        (progn
        (setq yakusu 0)
        (loop for j from 1 while (<= (* j j) i) do
            (if (zerop (rem i j))
            (progn
                (incf yakusu)
                (if (not (= (* j j) i))
                    (incf yakusu)
                )
            )
            )
        )
        (if (= yakusu 8)
            (incf ans)
        )
        )
    )
    (princ ans )
)

Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


(defparameter n (read))
(defparameter target-list (loop for i from 1 to n by 2 collect i))

(defun count-8 ()
  (count 8 (mapcar #'calc-divisor target-list)))

(defun calc-divisor (num)
  (loop for i from 1 to num count (= 0 (mod num i))))

(princ (count-8))


#-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 (str k)
  (if (every (lambda (x) (char= x #\1)) (subseq str 0 (min (length str) k)))
      #\1
      (loop for i across str
            when (null (char= i #\1))
              do (return i))))

(princ (main (read-string) (read)))

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

S is a string of length between 1 and 100 (inclusive).

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


(defun checktrain (a)
  (count-if #'(lambda (n)
                (and (>= (car n) (car a)) (<= (cdr n) (cdr a)))) *train*))
(defparameter *city* (read))
(defparameter *n-train* (read))
(defparameter *n-q* (read))
(defparameter *train* (loop :for s :from 1 :upto *n-train* collect(cons (read) (read))))
(defparameter *q* (loop :for l :from 1 :upto *n-q* collect(cons (read) (read))))
(loop :for w :from 1 :upto *n-q* do(format t "~A~%" (checktrain (nth (1- w) *q*))))

Score: 400 points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east.
A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i).
Takahashi the king is interested in the following Q matters:

The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

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

M is an integer between 1 and 200 \ 000 (inclusive).

Q is an integer between 1 and 100 \ 000 (inclusive).

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

1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City 1 to 7. There is only one train that runs strictly within that section: Train 1.
The second query is on the section from City 3 to 10. There is only one train that runs strictly within that section: Train 3.

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10


Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


(let* ((n (read)) (max-q (nth-value 0 (floor n 7))) (flag 0))
  (dotimes (i (1+ max-q))
    (if (= (mod (- n (* i 7)) 4) 0)
      (progn (setq flag 1) (return))))
  (princ (if (= flag 1) "Yes" "No")))

Score : 200 points

Problem Statement

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each.
Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be 4 + 7 = 11 dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be 4 \times 10 = 40 dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (4 dollars) and doughnuts (7 dollars) are both higher than 3 dollars, so there is no such way.


(defparameter yen (read))
(defparameter stk (list 0))
(defun lp ()
  (princ stk)
  (cond ((= (reduce #'+ stk) yen) (princ "Yes"))
        ((< (reduce #'+ stk) yen) (push 4 stk) (lp))
        ((= (first stk) 0) (princ "No"))
        ((= (pop stk) 4) (pop stk) (push 7 stk) (lp))
        (t (lp))))


(let ((a (read)))
  (if (or (= 0 (mod (mod a 7) 4)) (= 0 (mod a 7)))
      (princ "Yes")
      (princ "No")))


(let ((a (read)))
  (if (or (= 4 (mod a 7)) (= 0 (mod a 7)))
      (princ "Yes")
      (princ "No")))


Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


(let ((rate (read)))
  (cond
    ((< rate 1200) (princ "ABC"))
    ((< rate 2800) (princ "ARC"))
    (t (princ "AGC"))))


(let ((s (read-line)))
  (princ (if (and (char= (char s 0) #\A)
                  (= 1 (count #\C s :start 2 :end (- (length s) 1) :test #'char=))
                  (not (some #'upper-case-p (remove #\C (subseq s 2) :count 1))))
    "AC"
    "WA")))

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


(let ((str (read-line)))
  (defun char-down-p (a)
    (<= 97 (char-code a) 122))
  (if (and (char= #\A (aref str 0))
           (= 1 (count #\C (subseq str 2 (- (length str) 1)) :test #'char=))
           (equal "AC" (remove-if #'char-down-p str)))
      (princ "AC")
      (princ "WA")))


(defun chkchartype (a)
  (and (>= (char-code a) 97) (<= (char-code a) 122)))

(let ((str (concatenate 'list (read-line))))
  (if (and (char= #\A (pop str)) (chkchartype (pop str)) (char= #\C (pop str)) (string= (concatenate 'string str) (string-downcase (concatenate 'string str))))
      (princ "AC")
      (princ "WA")))


(let ((s (read-line)))
  (princ (if (and (char= (char s 0) #\A)
                  (= (count #\C (subseq s 2 (1- (length s)))) 1)
                  (string= (remove-if #'lower-case-p (remove #\C (subseq s 1) :count 1)) ""))
             "AC"
             "WA")))


(let ((s (read-line)))
  (princ (if (and (equal (char s 0) #\A) (= 1 (count #\C (subseq s 2)))) "AC" "WA")))


(defun calc (l)
  (+ (abs (- (nth 1 l) (nth 0 l))) (abs (- (nth 2 l) (nth 1 l)))))

(defun perm (now next)
  (let ((minimum 1000000000) (tmp nil))
    (if (equal now nil)
      (calc next)
      (dotimes (i (length now) minimum)
               (setq tmp (perm (append (subseq now 0 i) (nthcdr (+ i 1) now)) (append next (list (nth i now)))))
               (when (> minimum tmp) (setq minimum tmp))))))

(format t "~a~%" (perm (list (read) (read) (read)) '()))

Score : 100 points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost 0.

Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.

Here, |x| denotes the absolute value of x.

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be 5, which is the minimum:

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


(defun TaskSchedulingProblem (tList)
  (sort tList #'<)
  (+ (- (cadr tList) (car tList)) (- (caddr tList) (cadr tList))))

(format t "~A~%" (TaskSchedulingProblem (list (read) (read) (read))))


(let ((a (read))
      (b (read))
      (c (read)))
 (princ (- (max a b c) (min a b c))))


(let ((l1 (concatenate 'list (read-line)))
      (l2 (concatenate 'list (read-line))))

  (defun f (lst)
    (reverse (cdr (reverse (append (last lst) lst)))))

  (defun g (lst1 lst2 &optional (cnt (length lst1)))
    (if (minusp cnt)
      nil
      (if (equal lst1 lst2)
        T
        (g (f lst1) lst2 (1- cnt)))))

  (format t "~A~%"
          (if (g l1 l2)
            "Yes"
            "No")))

Score : 200 points

Problem Statement

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print Yes; if it does not, print No.

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


(princ (reduce (lambda (x y) (+ x (1- y)))
	(loop :repeat (read) :collect (read))
	:initial-value 0))

Score : 300 points

Problem Statement

You are given N positive integers a_1, a_2, ..., a_N.

For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).

Here, X\ mod\ Y denotes the remainder of the division of X by Y.

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


(let* ((n (read))
       (lst (loop :repeat n :collect (read))))
  (princ (loop :for a :from 1 :upto (reduce #'* lst)
               :maximize(reduce #'+ (mapcar (lambda (k) (mod a k)) lst)))))


(read-line) ; Drop the first line.
(princ
 (apply #'+
        (mapcar #'(lambda (x)
                    (1- x))
                (read-from-string (concatenate 'string "(" (read-line) ")")))))


(let ((land-num (read))
      (request-num (read))
      (lands (make-array (1+ land-num))))
  (loop repeat request-num
        for land1 = (read)
        for land2 = (read)
        do (setf (aref lands land2) (max land1 (aref lands land2))))
  (loop with ans = 0
        for i from 1 upto land-num
        do (and (not (= 0 (aref lands i)))
                (= (aref lands (aref lands i)) ans)
                (incf ans))
           (setf (aref lands i) ans)
        finally (format t "~A~%" ans)))

Score : 400 points

Problem Statement

There are N islands lining up from west to east, connected by N-1 bridges.

The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.

One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:

Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible.

You decided to remove some bridges to meet all these M requests.

Find the minimum number of bridges that must be removed.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq a_i < b_i \leq N

All pairs (a_i, b_i) are distinct.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the minimum number of bridges that must be removed.

Sample Input 1

5 2
1 4
2 5

Sample Output 1

1

The requests can be met by removing the bridge connecting the second and third islands from the west.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

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

Sample Output 3

4


(let (ilands)
  (defun init-irands (n)
    (setq ilands (loop repeat n collect 1)))

  (defun remove-bridge (iland1 iland2)
    (if (not (find 0 (subseq ilands (1- iland1) (1- iland2))))
        (setq ilands (concatenate 'list (subseq ilands 0 (- iland2 2)) '(0) (subseq ilands (1- iland2))))))

  (defun get-ilands ()
    ilands))

(defun get-requests (m)
  (loop repeat m collect (list (read) (read))))

(defun merge-sort (sequence)
  (let ((split (floor (length sequence) 2)))
    (if (zerop split)
        (copy-seq sequence)
        (merge 'list
               (merge-sort (subseq sequence 0 split))
               (merge-sort (subseq sequence split))
               #'(lambda (a b) (< (cadr a) (cadr b)))))))

(defun Islands-War ()
  (init-irands (read))
  (let ((requests (merge-sort (get-requests (read)))))
    (labels ((islands-war (requests cnt)
               (if requests
                   (if (remove-bridge (caar requests) (cadar requests))
                       (islands-war (cdr requests) (1+ cnt))
                       (islands-war (cdr requests) cnt))
                   cnt)))
      (islands-war requests 0))))

(Islands-War)


(let (ilands)
  (defun init-irands (n)
    (setq ilands (loop repeat n collect 1)))

  (defun remove-bridge (iland1 iland2)
    (if (find 0 (subseq ilands (1- iland1) (1- iland2)))
        ilands
        (setq ilands (concatenate 'list (subseq ilands 0 (- iland2 2)) '(0) (subseq ilands (1- iland2))))))

  (defun get-ilands ()
    ilands))

(defun get-requests (m)
  (loop repeat m collect (list (read) (read))))

(defun Islands-War ()
  (init-irands (read))
  (loop for request in (sort (get-requests (read)) #'(lambda (a b) (< (cadr a) (cadr b)))) do
    (remove-bridge (first request) (second request)))
  (princ (count 0 (get-ilands))))

(Islands-War)


(let ((n (read))
      (pre -1)
      (rep 0)
      (temp 0)
      (ans 0))
  (loop repeat n do
        (setf temp (read))
        (if (eq pre temp) (progn (incf rep)
                                 (if (eq 0 (rem rep 2)) (incf ans)))
            (progn (setf pre temp)
                   (setf rep 1))))
  (princ ans))

Score : 200 points

Problem Statement

Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000.

Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i.
If two slimes of the same color are adjacent, they will start to combine themselves. Because Takahashi likes smaller slimes, he has decided to change the colors of some of the slimes with his magic.

Takahashi can change the color of one slime to any of the 10000 colors by one spell.
How many spells are required so that no slimes will start to combine themselves?

Constraints

2 \leq N \leq 100

1 \leq a_i \leq N

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 the minimum number of spells required.

Sample Input 1

5
1 1 2 2 2

Sample Output 1

2

For example, if we change the color of the second slime from the left to 4, and the color of the fourth slime to 5, the colors of the slimes will be 1, 4, 2, 5, 2, which satisfy the condition.

Sample Input 2

3
1 2 1

Sample Output 2

0

Although the colors of the first and third slimes are the same, they are not adjacent, so no spell is required.

Sample Input 3

5
1 1 1 1 1

Sample Output 3

2

For example, if we change the colors of the second and fourth slimes from the left to 2, the colors of the slimes will be 1, 2, 1, 2, 1, which satisfy the condition.

Sample Input 4

14
1 2 2 3 3 3 4 4 4 4 1 2 3 4

Sample Output 4

4


(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
(defun displace (vec &optional (start 0) end)
  "displaced subseq"
  (let ((end (or end (length vec))))
    (make-array (- end start)
                :element-type (array-element-type vec)
                :displaced-to vec
                :displaced-index-offset start)))

(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 (inline simple-base-string40=))
(defun simple-base-string40= (s1 s2)
  (declare #.OPT
           ((simple-base-string 40) s1 s2))
  (equal s1 s2))

(declaim (inline sxhash-sbs40))
(defun sxhash-sbs40 (string)
  (declare #.OPT
           ((simple-base-string 40) string))
  (macrolet ((set-result (form)
               `(setf result (ldb (byte 64 0) ,form))))
    (let ((result 0))
      (declare (uint64 result))
      (dotimes (i 5)
        (set-result (+ result (sb-kernel:%vector-raw-bits string i)))
        (set-result (logxor result (ash result -6))))
      (set-result (logxor result (ash result -11)))
      (logand result most-positive-fixnum))))

(sb-ext:define-hash-table-test simple-base-string40= sxhash-sbs40)

(declaim (inline extract))
(defun extract (mask s)
  (let* ((res (make-string 40 :element-type 'base-char :initial-element #\Nul)))
    (loop with red-i = 0
          with blue-i = 20
          for pos below (length s)
          do (if (logbitp pos mask)
                 (progn (setf (aref res red-i) (aref s pos))
                        (incf red-i))
                 (progn (setf (aref res  blue-i) (aref s pos))
                        (incf blue-i))))
    res))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (s (read-line))
         (s1 (coerce (reverse (displace s 0 n)) 'simple-base-string))
         (s2 (coerce (displace s n (+ n n)) 'simple-base-string))
         (table (make-hash-table :test #'simple-base-string40= :size #.(expt 2 18))))
    (declare ((integer 1 18) n))
    (dotimes (mask (expt 2 n))
      (let ((key (extract mask s1)))
        (multiple-value-bind (value presentp) (gethash key table)
          (if presentp
              (setf (gethash key table) (1+ (the uint32 value)))
              (setf (gethash key table) 1)))))
    (let ((res 0))
      (declare (fixnum res))
      (dotimes (mask (expt 2 n))
        (let* ((key (extract mask s2))
               (value (gethash key table)))
          (when value
            (incf res (the uint32 value)))))
      (println res))))

#-swank(main)

Score : 600 points

Problem Statement

You are given a string S of length 2N consisting of lowercase English letters.

There are 2^{2N} ways to color each character in S red or blue. Among these ways, how many satisfy the following condition?

The string obtained by reading the characters painted red from left to right is equal to the string obtained by reading the characters painted blue from right to left.

Constraints

1 \leq N \leq 18

The length of S is 2N.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of ways to paint the string that satisfy the condition.

Sample Input 1

4
cabaacba

Sample Output 1

4

There are four ways to paint the string, as follows:

cabaacba

cabaacba

cabaacba

cabaacba

Sample Input 2

11
mippiisssisssiipsspiim

Sample Output 2

504

Sample Input 3

4
abcdefgh

Sample Output 3

0

Sample Input 4

18
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Sample Output 4

9075135300

The answer may not be representable as a 32-bit integer.


(let ((s (read-line))
      (n (read)))
  (loop for i from 0 upto (floor (/ (- (length s) 1) n)) do (format t "~a" (char s (* i n))))
  (format t "~%"))

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters.
We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom.

Constraints

1 \leq w \leq |S| \leq 1000

S consists of lowercase English letters.

w is an integer.

Input

Input is given from Standard Input in the following format:

S
w

Output

Print the desired string in one line.

Sample Input 1

abcdefgh
3

Sample Output 1

adg

When we write down abcdefgh, starting a new line after every three letters, we get the following:

abc

def

gh

Concatenating the letters at the beginnings of these lines, we obtain adg.

Sample Input 2

lllll
1

Sample Output 2

lllll

Sample Input 3

souuundhound
2

Sample Output 3

suudon


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

;; BEGIN_INSERTED_CONTENTS
(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (terminate-char #\Space))
  "Note that the returned string will be reused."
  (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))
       (loop for ,character of-type base-char =
                #-swank (code-char (read-byte ,in nil #\Newline))
                #+swank (read-char ,in nil #\Newline)
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (setf (schar ,buffer ,idx) ,terminate-char)
                     (return (values ,buffer ,idx))))))

(defmacro split-ints-and-bind (vars string &body body)
  (let ((pos1 (gensym "POS"))
	(pos2 (gensym "POS"))
	(str (gensym "STR")))
    (labels ((expand (vars &optional (init-pos1 t))
	       (if (null vars)
		   body
		   `((let* ((,pos1 ,(if init-pos1 0 `(1+ ,pos2)))
			    (,pos2 (position #\space ,str :start ,pos1 :test #'char=))
			    (,(car vars) (parse-integer ,str :start ,pos1 :end ,pos2)))
		       ,@(expand (cdr vars) nil))))))
      `(let ((,str ,string))
         (declare (string ,str))
	 ,@(expand vars)))))

(defstruct (heap (:constructor make-heap
                            (size
                             &key test (element-type t)
                             &aux (data (make-array (1+ size) :element-type element-type)))))
  (data #() :type (simple-array * (*)) :read-only t)
  (test #'< :type function :read-only t)
  (next-position 1 :type (integer 1 #.most-positive-fixnum)))

(declaim (inline heap-push))
(defun heap-push (obj heap)
  (symbol-macrolet ((data (heap-data heap))
                    (test (heap-test heap))
                    (next-position (heap-next-position heap)))
    (labels ((update (pos)
               (unless (= pos 1)
                 (let ((parent-pos (floor pos 2)))
                   (when (funcall test (aref data pos) (aref data parent-pos))
                     (rotatef (aref data pos) (aref data parent-pos))
                     (update parent-pos))))))
      (setf (aref data next-position) obj)
      (update next-position)
      (incf next-position)
      heap)))

(declaim (inline heap-pop))
(defun heap-pop (heap &optional (error t) null-value)
  (symbol-macrolet ((data (heap-data heap))
                    (test (heap-test heap))
                    (next-position (heap-next-position heap)))
    (labels ((update (pos)
               (declare ((integer 1 #.most-positive-fixnum) pos))
               (let* ((child-pos1 (+ pos pos))
                      (child-pos2 (1+ child-pos1)))
                 (when (<= child-pos1 next-position)
                   (if (<= child-pos2 next-position)
                       (if (funcall test (aref data child-pos1) (aref data child-pos2))
                           (unless (funcall test (aref data pos) (aref data child-pos1))
                             (rotatef (aref data pos) (aref data child-pos1))
                             (update child-pos1))
                           (unless (funcall test (aref data pos) (aref data child-pos2))
                             (rotatef (aref data pos) (aref data child-pos2))
                             (update child-pos2)))
                       (unless (funcall test (aref data pos) (aref data child-pos1))
                         (rotatef (aref data pos) (aref data child-pos1))))))))
      (if (= next-position 1)
          (if error
              (error "No element in heap")
              null-value)
          (prog1 (aref data 1)
            (decf next-position)
            (setf (aref data 1) (aref data next-position))
            (update 1))))))

(defun heap-peak (heap &optional (error t) null-value)
  (if (= 1 (heap-next-position heap))
      (if error
          (error "No element in heap")
          null-value)
      (aref (heap-data heap) 1)))

;; For test
;; (eval-when (:compile-toplevel :load-toplevel :execute)
;;   (ql:quickload :fiveam)
;;   (use-package :fiveam))

;; (test heap-test
;;   (let ((h (make-heap 20)))
;;     (finishes (dolist (o (list 7 18 22 15 27 9 11))
;;                 (heap-push o h)))
;;     (is (= 7 (heap-peak h)))
;;     (is (equal '(7 9 11 15 18 22 27)
;;                (loop repeat 7 collect (heap-pop h))))
;;     (signals error (heap-pop h))
;;     (is (eql 'eof (heap-pop h nil 'eof)))
;;     (is (eql 'eof (heap-peak h nil 'eof))))
;;   (is (typep (heap-data (make-heap 10 :element-type 'fixnum))
;;              '(simple-array fixnum (*)))))

;; (run! 'heap-test)

(defun bench (&optional (size 2000000))
  (declare (optimize (speed 3)))
  (let* ((heap (make-heap size :element-type 'fixnum))
         (seed (seed-random-state 0)))
    (time (dotimes (i size)
            (heap-push (random most-positive-fixnum seed) heap)))
    (time (dotimes (i size)
            (heap-pop heap)))))

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

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

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (let* ((n (read))
         (m (read))
         (src (- (read) 1))
         (dest (- (read) 1))
         ;; (to . cost)
         (graph-yen (make-array n :element-type 'list :initial-element nil))
         (graph-snook (make-array n :element-type 'list :initial-element nil))
         (yen-table (make-array n :element-type 'fixnum :initial-element most-positive-fixnum))
         (snook-table (make-array n :element-type 'fixnum :initial-element most-positive-fixnum)))
    (dotimes (i m)
      (split-ints-and-bind (u v a b) (buffered-read-line 50)
        (push (cons (- v 1) a) (aref graph-yen (- u 1)))
        (push (cons (- u 1) a) (aref graph-yen (- v 1)))
        (push (cons (- v 1) b) (aref graph-snook (- u 1)))
        (push (cons (- u 1) b) (aref graph-snook (- v 1)))))
    (let ((pqueue (make-heap 200000 :test (lambda (p1 p2) (< (cdr p1) (cdr p2)))
                                    :element-type '(cons uint32 fixnum)))
          (visited (make-array n :element-type 'boolean :initial-element nil)))
      (heap-push (cons src 0) pqueue)
      (loop for (current . cost) = (heap-pop pqueue nil '(-1 . -1))
            until (= current -1)
            do (unless (aref visited current)
                 (setf (aref visited current) t)
                 (when (< cost (aref yen-table current))
                   (setf (aref yen-table current) cost))
                 (dolist (neighbor (aref graph-yen current))
                   (heap-push (cons (car neighbor) (+ cost (cdr neighbor))) pqueue)))))
    (let ((pqueue (make-heap 200000 :test (lambda (p1 p2) (< (cdr p1) (cdr p2)))
                                    :element-type '(cons uint32 fixnum)))
          (visited (make-array n :element-type 'boolean :initial-element nil)))
      (heap-push (cons dest 0) pqueue)
      (loop for (current . cost) = (heap-pop pqueue nil '(-1 . -1))
            until (= current -1)
            do (unless (aref visited current)
                 (setf (aref visited current) t)
                 (when (< cost (aref snook-table current))
                   (setf (aref snook-table current) cost))
                 (dolist (neighbor (aref graph-snook current))
                   (heap-push (cons (car neighbor) (+ cost (cdr neighbor))) pqueue)))))
    (let ((hub-to-cost (make-array n :element-type 'fixnum))
          (year-to-cost (make-array n :element-type 'fixnum)))
      (dotimes (i n)
        (setf (aref hub-to-cost i)
              (- #.(expt 10 15) (+ (aref yen-table i) (aref snook-table i)))))
      (loop for y from (- n 1) downto 0 ; (i-1)-th exchange is closed after i years.
                                        ; i is opened.
            maximize (aref hub-to-cost y) into current-max
            do (setf (aref year-to-cost y) current-max))
      (dotimes (y n)
        (println (aref year-to-cost y))))))

#-swank(main)

Score : 400 points

Problem Statement

Kenkoooo is planning a trip in Republic of Snuke.
In this country, there are n cities and m trains running.
The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally.
Any city can be reached from any city by changing trains.

Two currencies are used in the country: yen and snuuk.
Any train fare can be paid by both yen and snuuk.
The fare of the i-th train is a_i yen if paid in yen, and b_i snuuk if paid in snuuk.

In a city with a money exchange office, you can change 1 yen into 1 snuuk.
However, when you do a money exchange, you have to change all your yen into snuuk.
That is, if Kenkoooo does a money exchange when he has X yen, he will then have X snuuk.
Currently, there is a money exchange office in every city, but the office in City i will shut down in i years and can never be used in and after that year.

Kenkoooo is planning to depart City s with 10^{15} yen in his pocket and head for City t, and change his yen into snuuk in some city while traveling.
It is acceptable to do the exchange in City s or City t.

Kenkoooo would like to have as much snuuk as possible when he reaches City t by making the optimal choices for the route to travel and the city to do the exchange.
For each i=0,...,n-1, find the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i years.
You can assume that the trip finishes within the year.

Constraints

2 \leq n \leq 10^5

1 \leq m \leq 10^5

1 \leq s,t \leq n

s \neq t

1 \leq u_i < v_i \leq n

1 \leq a_i,b_i \leq 10^9

If i\neq j, then u_i \neq u_j or v_i \neq v_j.

Any city can be reached from any city by changing trains.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m s t
u_1 v_1 a_1 b_1
:
u_m v_m a_m b_m

Output

Print n lines.
In the i-th line, print the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i-1 years.

Sample Input 1

4 3 2 3
1 4 1 100
1 2 1 10
1 3 20 1

Sample Output 1

999999999999998
999999999999989
999999999999979
999999999999897

After 0 years, it is optimal to do the exchange in City 1.

After 1 years, it is optimal to do the exchange in City 2.

Note that City 1 can still be visited even after the exchange office is closed.
Also note that, if it was allowed to keep 1 yen when do the exchange in City 2 and change the remaining yen into snuuk, we could reach City 3 with 999999999999998 snuuk, but this is NOT allowed.

After 2 years, it is optimal to do the exchange in City 3.

After 3 years, it is optimal to do the exchange in City 4.
Note that the same train can be used multiple times.

Sample Input 2

8 12 3 8
2 8 685087149 857180777
6 7 298270585 209942236
2 4 346080035 234079976
2 5 131857300 22507157
4 8 30723332 173476334
2 6 480845267 448565596
1 4 181424400 548830121
4 5 57429995 195056405
7 8 160277628 479932440
1 6 475692952 203530153
3 5 336869679 160714712
2 7 389775999 199123879

Sample Output 2

999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994


(in-package :cl-user)
(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 (set-dispatch-macro-character #\# #\> #'cl-debug-print:debug-print-reader)

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

(defconstant +mod+ 1000000007)

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

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

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read)))
    (println (if (evenp n) n (* n 2)))))

#-swank (main)

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

#+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* (or out (make-string-output-stream)))
         (res (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))))))
    (if out res (get-output-stream-string *standard-output*))))

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

#-swank
(eval-when (:compile-toplevel)
  (when (and (boundp 'sb-c::*compiler-warning-count*)
             (> sb-c::*compiler-warning-count* 0))
    (sb-ext:quit :unix-status 1)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (5am:is
   (equal "6
"
          (run "3
" nil)))
  (5am:is
   (equal "10
"
          (run "10
" nil)))
  (5am:is
   (equal "1999999998
"
          (run "999999999
" nil))))

Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


(defun solve(n)
  (if (= (mod n 2) 0))
  (princ n)
  (princ (* n 2)))

(format t "~A" (solve (read)))


(defvar *N* nil)
(setf *N* (read))

(defvar *count* *N*)
(defvar *list1* (list nil))
(dotimes (x 10)
  (declare (ignore x))
  (if (= (mod *count* *N*) 0)
      (push *count* *list1*))
  (setq *count* (+ *count* *N*)))

(setq *list1* (cdr (reverse *list1*)))

(setq *count* *N*)
(defvar *list2* (list nil))
(dotimes (x 10)
  (declare (ignore x))
  (when (= (mod *count* 2) 0)
      (push *count* *list2*))
  (setq *count* (+ *count* *N*)))

(setq *list2* (cdr (reverse *list2*)))

(dolist (x *list1*)
  (dolist (y *list2*)
    (if (= x y)
        (progn (format t "~d~%" x)
               (sb-ext:quit)))))


(let ((a (sort (loop repeat (read) collect (read)) #'<)))
     (princ (- (first (last a))
               (first a))))

Score : 200 points

Problem Statement

You are given an integer sequence A of length N.
Find the maximum absolute difference of two elements (with different indices) in A.

Constraints

2 \leq N \leq 100

1 \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

Print the maximum absolute difference of two elements (with different indices) in A.

Sample Input 1

4
1 4 6 3

Sample Output 1

5

The maximum absolute difference of two elements is A_3-A_1=6-1=5.

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


(let* ((n (read))
       (l (sort (loop repeat n
                      collect (read))
                #'>)))

  (format t "~A~%"
          (- (car l)
             (car (last l)))))


# include <iostream>
# include <string>

int main()
{
    std::string s, t;
    std::cin >> s >> t;
    int n = s.length();

    int flag = 0;
    for (int i=0; i<n; i++) {
        std::string rotated;
        rotated = s.substr(i) + s.substr(0, i);    // string型のもつsubstrメソッドで部分文字列を取れる。 + で連結も可能
        if (rotated == t) {
            flag = 1;
            break;
        }
    }
    if (flag) {
        std::cout << "Yes" << std::endl;
    } else {
        std::cout << "No" << std::endl;
    }
}


(defun moge ()
  (let ((n (read))
        (lst nil))
    (dotimes (i n)
      (push (read) lst))
    (reverse lst)))

(defun keisan (lst b-lst)
  (loop :for b :in b-lst
        :collect (loop :for a :in lst
                       :for i :from 1
                       :sum (abs (- a (+ b i))))))

(defun hoge ()
  (let* ((lst (moge))
         (b-lst (loop :for a :in lst
                      :for i :from 1
                      :collect (- a i)))
         (v (keisan lst b-lst)))
    (format t "~D~%" (apply #'min v))))

(hoge)

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

He will freely choose an integer b.
Here, he will get sad if A_i and b+i are far from each other.
More specifically, the sadness of Snuke is calculated as follows:

abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))

Here, abs(x) is a function that returns the absolute value of x.

Find the minimum possible sadness of Snuke.

Constraints

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

1 \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

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

If we choose b=0, the sadness of Snuke would be abs(2-(0+1))+abs(2-(0+2))+abs(3-(0+3))+abs(5-(0+4))+abs(5-(0+5))=2.
Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


(defun sad-diff (N newlst)
  (- (* 2 (count-if #'minusp newlst)) N))

(defun range (m n &optional l)
  (if (< n m) l
    (range m (1- n) (cons n l)) ))

(defun solve (N lst)
  (setf lst (mapcar #'- lst (range 1 N)))
  (let ((m (reduce #'min lst))
        (n (reduce #'max lst)))
       (do* ((b m (1+ b))
             (l (mapcar (lambda (x) (- x b)) lst)
                (mapcar #'1- lst))
             (sad (reduce
                   (lambda (x y) (+ x (abs y)))
                   l :initial-value 0 )
                  (+ sad (sad-diff N l)))
             (minsad sad (min sad minsad)))
         ((> b n) minsad) )))

(defvar N (read))
(princ (solve N (loop :repeat N :collect (read))))


(defun LinearApproximation ()
  (let ((B) (sb 0) (count 0) (*n* (read)))
    (dotimes (i *n*)
      (push  (- (read) (1+ i)) B))
    (sort B #'<)
    (setf sb  (nth (floor *n* 2) B))
    (apply #'+ (mapcar (lambda (Bi)
               (abs (- Bi sb))) B))))

(format t "~A~%" (LinearApproximation))


(defparameter *n* (read))

(defun split-string (str)
  (let ((string-position (position #\Space str)))
    (cond
      ((null string-position) (list str))
      (t (cons (subseq str 0 string-position) (split-string (subseq str (1+ string-position))))))))

(defun LinearApproximation ()
  (let ((B) (sb 0) (count 0))
    (dotimes (i *n*)
      (push  (- (read) (1+ i)) B))
    (sort B #'<)
    (setf sb  (nth (floor *n* 2) B))
    (apply #'+ (mapcar (lambda (Bi)
               (abs (- Bi sb))) B))))

(format t "~A~%" (LinearApproximation))


;; WA
(defun subi (a xs)
  (if (null xs)
      ()
    (cons (- a (car xs)) (subi a (cdr xs)))))

(let ((N (read))
      A)
  (format t "~A~%"
          (apply #'+
                 (mapcar #'abs
                         (let ((sorted (sort
                                        (dotimes (i N A) (push (- (read) i 1) A))
                                        #'<)))
                           (subi
                            (nth (1- (ceiling (/ (length A) 2))) sorted) A))))))


(defun subi (a xs)
  (if (null xs)
      ()
    (cons (- a (car xs)) (subi a (cdr xs)))))

(let ((N (read))
      A)
  (format t "~A~%"
          (apply #'+
                 (mapcar #'abs
                         (let ((sorted (sort
                                        (dotimes (i N A) (push (- (read) i 1) A))
                                        #'<)))
                           (subi
                            (nth (floor (/ (length A) 2)) sorted) A))))))


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

;; BEGIN_INSERTED_CONTENTS
(declaim (inline unique-merge))
(defun unique-merge (list1 list2 order &key (key #'identity) end)
  (declare (function order))
  (labels
      ((recur (list1 list2 len)
         (declare ((integer 0 #.most-positive-fixnum) len))
         (cond
           ((zerop len) nil)
           ((null list1) list2)
           ((null list2) list1)
           (t
            (let ((val1 (funcall key (car list1)))
                  (val2 (funcall key (car list2))))
              (cond ((funcall order val1 val2)
                     (cons (car list1)
                           (recur (cdr list1) list2 (- len 1))))
                    ((funcall order val2 val1)
                     (cons (car list2)
                           (recur list1 (cdr list2) (- len 1))))
                    ((eql (car list1) (car list2))
                     (cons (car list1)
                           (recur (cdr list1) (cdr list2) (- len 1))))
                    (t
                     (cons (car list1)
                           (recur (cdr list1) list2 (- len 1))))))))))
    (recur list1 list2 (or end most-positive-fixnum))))

;; Should we do this with UNWIND-PROTECT?
(defmacro with-buffered-stdout (&body body)
  "Buffers all outputs to *STANDARD-OUTPUT* in BODY and flushes them to
*STANDARD-OUTPUT* after BODY has been done (without error). Note that only
BASE-CHAR is allowed."
  (let ((out (gensym)))
    `(let ((,out (make-string-output-stream :element-type 'base-char)))
       (let ((*standard-output* ,out))
         ,@body)
       (write-string (get-output-stream-string ,out)))))

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(declaim (inline zeta-subtransform!))
(defun zeta-subtransform! (vector &optional (plus #'+))
  (declare (vector vector))
  (let* ((n (length vector))
         ;; cardinality of the underlying set
         (card (- (integer-length n) 1)))
    (assert (= 1 (logcount n)))
    (dotimes (i card)
      (let ((mask (ash 1 i)))
        (dotimes (j n)
          (unless (zerop (logand j mask))
            (setf (aref vector j)
                  (funcall plus
                           (aref vector j)
                           (aref vector (logxor j mask))))))))
    vector))

(declaim (inline moebius-subtransform!))
(defun moebius-subtransform! (vector &optional (minus #'-))
  (declare (vector vector))
  (let* ((n (length vector))
         (card (- (integer-length n) 1)))
    (assert (= 1 (logcount n)))
    (dotimes (i card)
      (let ((mask (ash 1 i)))
        (dotimes (j n)
          (unless (zerop (logand j mask))
            (setf (aref vector j)
                  (funcall minus
                           (aref vector j)
                           (aref vector (logxor j mask))))))))
    vector))

;; 添え字集合∪添え字集合で大きいほう2つを残すという操作を⊕とすると、結合的かつ可換。
;; つまり、F(S) = ⊕_{T ⊆ S} f(T)を求めれば良いけど、fは何？
;; → f(T) = {T}か。
;; これでi∨j ⊆ K に対する最大値は求まる。
;; i∨j <= K ⇔ k∈[K]が存在してi∨j = k
;; ⇒ k∈[K]が存在してi∨j⊆k
;; 最後は逆も成り立つ。k∈[K]が与えられたとき、任意のl⊆kについてl∈Kだから

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (power (expt 2 n))
         (as (make-array power :element-type 'uint32))
         (dp (make-array power :element-type 'list)))
    (declare ((integer 1 18) n))
    (dotimes (i power)
      (setf (aref as i) (read-fixnum)
            (aref dp i) (list i)))
    (zeta-subtransform!
     dp
     (lambda (set1 set2)
       (unique-merge (copy-list set1)
                     (copy-list set2)
                     #'>
                     :key (lambda (x) (aref as x))
                     :end 2)))
    (let ((res 0))
      (declare (uint32 res))
      (with-buffered-stdout
        (loop for x from 1 below power
              for (idx1 idx2) = (aref dp x)
              do (setf res (max res (+ (aref as idx1) (aref as idx2))))
                 (println res))))))

#-swank (main)

Score : 700 points

Problem Statement

There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.)

For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem:

Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K.
Here, or denotes the bitwise OR.

Constraints

1 \leq N \leq 18

1 \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_0 A_1 ... A_{2^N-1}

Output

Print 2^N-1 lines.
In the i-th line, print the answer of the problem above for K=i.

Sample Input 1

2
1 2 3 1

Sample Output 1

3
4
5

For K=1, the only possible pair of i and j is (i,j)=(0,1), so the answer is A_0+A_1=1+2=3.

For K=2, the possible pairs of i and j are (i,j)=(0,1),(0,2).
When (i,j)=(0,2), A_i+A_j=1+3=4. This is the maximum value, so the answer is 4.

For K=3, the possible pairs of i and j are (i,j)=(0,1),(0,2),(0,3),(1,2),(1,3),(2,3) .
When (i,j)=(1,2), A_i+A_j=2+3=5. This is the maximum value, so the answer is 5.

Sample Input 2

3
10 71 84 33 6 47 23 25

Sample Output 2

81
94
155
155
155
155
155

Sample Input 3

4
75 26 45 72 81 47 97 97 2 2 25 82 84 17 56 32

Sample Output 3

101
120
147
156
156
178
194
194
194
194
194
194
194
194
194


(defun func (x)
  (if x
	(+ (if (char= (car x) #\+) 1 -1) (func (cdr x)))
	0))

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

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by 1; when he eats -, the integer in his mind decreases by 1.

The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is 0.

The first integer for him to eat is +. After eating it, the integer in his mind becomes 1.

The second integer to eat is -. After eating it, the integer in his mind becomes 0.

The third integer to eat is +. After eating it, the integer in his mind becomes 1.

The fourth integer to eat is +. After eating it, the integer in his mind becomes 2.

Thus, the integer in Takahashi's mind after he eats all the symbols is 2.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


(defun parse-int-ex (n)
  (cond ((stringp n) (parse-integer n))
        ((char= n #\1) 1)
        ((char= n #\2) 2)
        ((char= n #\3) 3)
        ((char= n #\4) 4)
        ((char= n #\5) 5)
        ((char= n #\6) 6)
        ((char= n #\7) 7)
        ((char= n #\8) 8)
        ((char= n #\9) 9)
        ((char= n #\0) 0)))
(defun f (k)
  (reduce #'+ (mapcar #'parse-int-ex (concatenate 'list (format nil "~A" k)))))
(let* ((n (read)))
  (if (= 0 (mod n (f n))) (princ "Yes") (princ "No")))

Score : 200 points

Problem Statement

Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(101) = 1 + 0 + 1 = 2.

Given an integer N, determine if S(N) divides N.

Constraints

1 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

If S(N) divides N, print Yes; if it does not, print No.

Sample Input 1

12

Sample Output 1

Yes

In this input, N=12.
As S(12) = 1 + 2 = 3, S(N) divides N.

Sample Input 2

101

Sample Output 2

No

As S(101) = 1 + 0 + 1 = 2, S(N) does not divide N.

Sample Input 3

999999999

Sample Output 3

Yes


;; -*- 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"
  (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 ()
  (let* ((n (read))
         (k (read))
         (as (make-array n :element-type 'uint31))
         (res 0))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)))
    (labels ((frob (as)
               (unless (= 1 (aref as 0))
                 (let ((prev 0)
                       passed)
                   (loop
                     (when passed
                       (setf (aref as prev) 1)
                       (return))
                     (loop for i from prev below (min (+ prev k) n)
                           do (when (= (aref as i) 1)
                                (setq passed t)))
                     (incf res)
                     (setq prev (min (- n 1) (+ prev (- k 1)))))))))
      (frob as)
      #>res
      (frob (reverse as))
      (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 "4 3
2 3 1 4
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 3
1 2 3
"
    "1
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "8 3
7 3 1 8 4 6 2 5
"
    "4
")))

Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


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

(defun solver ()
  (let ((k (read)) (count 0) current  (temp 1))
    (loop for i fixnum from 2 do
          (when (= count k) (return))
          (setf current (/ i (apply #'+ (int-to-digit i))))
          (when (<= temp current)
            (format t "~a~%" (1- i)) (incf count))
          (setf temp current))))

(solver)

Score : 500 points

Problem Statement

Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(123) = 1 + 2 + 3 = 6.

We will call an integer n a Snuke number when, for all positive integers m such that m > n, \frac{n}{S(n)} \leq \frac{m}{S(m)} holds.

Given an integer K, list the K smallest Snuke numbers.

Constraints

1 \leq K

The K-th smallest Snuke number is not greater than 10^{15}.

Input

Input is given from Standard Input in the following format:

K

Output

Print K lines. The i-th line should contain the i-th smallest Snuke number.

Sample Input 1

10

Sample Output 1

1
2
3
4
5
6
7
8
9
19


Score: 100 points

Problem Statement

E869120's and square1001's 16-th birthday is coming soon.

Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.

E869120 and square1001 were just about to eat A and B of those pieces, respectively,

when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".

Can both of them obey the instruction in the note and take desired numbers of pieces of cake?

Constraints

A and B are integers between 1 and 16 (inclusive).

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(.

Sample Input 1

5 4

Sample Output 1

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 2

8 8

Sample Output 2

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 3

11 4

Sample Output 3

:(

In this case, there is no way for them to take desired number of pieces, unfortunately.


(defun div2count (N)
  (let ((str (format nil "~B" N)))
    (1- (- (length str)
	   (position #\1 str :from-end t)) )))

(defun solve (l)
  (reduce (lambda (x y) (+ x (div2count y)))
	  l :initial-value 0) )

(princ (solve (loop :repeat (read) :collect (read))))

Score: 300 points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3".
Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer.

At most how many operations can be performed?

Constraints

N is an integer between 1 and 10 \ 000 (inclusive).

a_i is an integer between 1 and 1 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially {5, 2, 4}. Three operations can be performed as follows:

First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}.

Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}.

Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 3}.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is 0.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39


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

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defparameter OPT
    #+swank '(optimize (speed 3) (safety 1))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))))

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

;; Hauptteil

(deftype uint nil `(integer 0 ,(expt 10 9)))

(defun count-2-as-factor (num)
  (loop with i = 0
        until (oddp num)
        do (setf num (ash num -1))
           (incf i)
        finally (return i)))

(defun main ()
  (let ((n (read)))
    (loop for i below n
          sum (count-2-as-factor (read)))))

#-swank(main)

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

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

;; Für Benchmark
#+swank(defparameter *this-path* *load-pathname*)
#+swank(defparameter *this-dir-path* (uiop:pathname-directory-pathname *this-path*))
#+swank(defparameter *dat-path* (merge-pathnames "test.dat" *this-dir-path*))

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

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


(defun fact (n)
  (if (< n 1)
      0
      (+ n (fact (1- n)))))

(defun solve (a b)
  (- (fact (- b a)) b))

(princ (solve (read) (read)))
(fresh-line)

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1


(let ((a (read))
      (b (read)))
  (princ (- (apply #'+ (loop for i from 1 upto (- b a) collect i)) b)))


(princ(/(-(expt(-(setq a(read))(setq b(read)))2)a b)2))


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

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

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

(defconstant +mod+ 1000000007)

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

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

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

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

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

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

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

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

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

(defun unwrap (list)
  (format nil "~{~a~^ ~}" list))

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

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

(defparameter *inf* 100000000)

(defun solve (n)
  (let ((memo (make-array (+ n 10)
                          :initial-element *inf*)))
    (setf (aref memo 0) 0)
    (loop for i from 0 to n do
         (loop with k = 9 while (<= (+ i k) n) do
              (setf (aref memo (+ i k))
                    (min (1+ (aref memo i))
                         (aref memo (+ i k))))
              (setf k (* k 9)))
         (loop with k = 6 while (<= (+ i k) n) do
              (setf (aref memo (+ i k))
                    (min (1+ (aref memo i))
                         (aref memo (+ i k))))
              (setf k (* k 6)))
         (setf (aref memo (1+ i))
               (min (1+ (aref memo i))
                    (aref memo (1+ i))))
       finally
         (return (aref memo n)))))

(defun main ()
  (declare #.OPT)
  (let ((n (read)))
    (format t "~a~&" (solve n))))

#-swank (main)

Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16


(let ((a (read))
      (b (read)))
(princ (max (+ a b)(- a b)(* a b))))

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest value among A+B, A-B and A \times B.

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


(let ((a (read))
      (b (read)))
  (princ (max (+ a b) (- a b) (* a b))))