;; -*- 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
(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

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

;; http://www.ambrsoft.com/trigocalc/circle3d.htm
;; FIXME: more sane handling of degeneracy
(declaim (inline calc-circumcenter))
(defun calc-circumcenter (p1 p2 p3)
  "Returns the center of circumcirlce if it exists, otherwise returns NIL."
  (declare (complex p1 p2 p3))
  (let* ((x1 (realpart p1))
         (y1 (imagpart p1))
         (x2 (realpart p2))
         (y2 (imagpart p2))
         (x3 (realpart p3))
         (y3 (imagpart p3))
         (a (+ (* x1 (- y2 y3))
               (- (* y1 (- x2 x3)))
               (* x2 y3)
               (- (* x3 y2))))
         (b (+ (* (+ (* x1 x1) (* y1 y1)) (- y3 y2))
               (* (+ (* x2 x2) (* y2 y2)) (- y1 y3))
               (* (+ (* x3 x3) (* y3 y3)) (- y2 y1))))
         (c (+ (* (+ (* x1 x1) (* y1 y1)) (- x2 x3))
               (* (+ (* x2 x2) (* y2 y2)) (- x3 x1))
               (* (+ (* x3 x3) (* y3 y3)) (- x1 x2)))))
    (handler-bind ((error (lambda (c)
                            (declare (ignore c))
                            (return-from calc-circumcenter nil))))
      (complex (- (/ b (* 2 a)))
               (- (/ c (* 2 a)))))))

(defun mini-disc-with-2-points (points end q1 q2 eps)
  "Returns the smallest circle that contains points, q1 and q2 (contains q1 and
q2 at the perimeter)."
  (declare (complex q1 q2)
           (double-float eps)
           ((integer 0 #.most-positive-fixnum) end))
  (let* ((center (* 0.5d0 (+ q1 q2)))
         (radius (abs (- q1 center))))
    (declare (complex center)
             (double-float radius))
    (dotimes (i end)
      (let ((new-point (aref points i)))
        (declare (complex new-point))
        (when (>= (abs (- new-point center)) (+ radius eps))
          (let ((new-center (calc-circumcenter q1 q2 new-point)))
            (setq center new-center
                  radius (abs (- new-point new-center)))))))
    (values center radius)))

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

(defun mini-disc-with-point (points end q eps)
  (declare (complex q)
           (double-float eps))
  (%shuffle! points end)
  (let* ((center (* 0.5d0 (+ (aref points 0) q)))
         (radius (abs (- q center))))
    (declare (complex center)
             (double-float radius))
    (loop for i from 1 below end
          for new-point of-type complex = (aref points i)
          when (>= (abs (- new-point center)) (+ radius eps))
          do (setf (values center radius)
                   (mini-disc-with-2-points points i (aref points i) q eps)))
    (values center radius)))

(defun calc-smallest-circle (points eps)
  (assert (>= (length points) 1))
  (when (= 1 (length points))
    (return-from calc-smallest-circle
      (values (aref points 0)
              (coerce 0 (type-of (realpart (aref points 0)))))))
  (let* ((points (copy-seq (%shuffle! points)))
         (copy (copy-seq points))
         (p0 (aref points 0))
         (p1 (aref points 1))
         (center (* 1/2 (+ p0 p1)))
         (radius (abs (- p0 center))))
    (loop for i from 2 below (length points)
          for new-point = (aref points i)
          when (>= (abs (- new-point center)) (+ radius eps))
          do (setf (values center radius)
                   (mini-disc-with-point copy i new-point eps)))
    (values center radius)))

(defun main ()
  (let* ((n (read))
         (points (make-array n :element-type '(complex double-float))))
    (declare (uint16 n))
    (dotimes (i n)
      (let ((x (float (read) 1d0))
            (y (float (read) 1d0)))
        (setf (aref points i) (complex x y))))
    (println (nth-value 1 (calc-smallest-circle points 1d-9)))))

#-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 "2
0 0
1 0
"
    "0.500000000000000000
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
0 0
0 1
1 0
"
    "0.707106781186497524
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10
10 9
5 9
2 0
0 0
2 7
3 3
2 5
10 0
3 7
1 9
"
    "6.726812023536805158
")))

Score : 600 points

Problem Statement

Given are N points (x_i, y_i) in a two-dimensional plane.

Find the minimum radius of a circle such that all the points are inside or on it.

Constraints

2 \leq N \leq 50

0 \leq x_i \leq 1000

0 \leq y_i \leq 1000

The given N points are all different.

The values in input are all integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum radius of a circle such that all the N points are inside or on it.

Your output will be considered correct if the absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

2
0 0
1 0

Sample Output 1

0.500000000000000000

Both points are contained in the circle centered at (0.5,0) with a radius of 0.5.

Sample Input 2

3
0 0
0 1
1 0

Sample Output 2

0.707106781186497524

Sample Input 3

10
10 9
5 9
2 0
0 0
2 7
3 3
2 5
10 0
3 7
1 9

Sample Output 3

6.726812023536805158

If the absolute or relative error from our answer is at most 10^{-6}, the output will be considered correct.


;; -*- 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
(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

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

;; http://www.ambrsoft.com/trigocalc/circle3d.htm
;; FIXME: more sane handling of degeneracy
(declaim (inline calc-circumcenter))
(defun calc-circumcenter (p1 p2 p3)
  "Returns the center of circumcirlce if it exists, otherwise returns NIL."
  (declare (complex p1 p2 p3))
  (let* ((x1 (realpart p1))
         (y1 (imagpart p1))
         (x2 (realpart p2))
         (y2 (imagpart p2))
         (x3 (realpart p3))
         (y3 (imagpart p3))
         (a (+ (* x1 (- y2 y3))
               (- (* y1 (- x2 x3)))
               (* x2 y3)
               (- (* x3 y2))))
         (b (+ (* (+ (* x1 x1) (* y1 y1)) (- y3 y2))
               (* (+ (* x2 x2) (* y2 y2)) (- y1 y3))
               (* (+ (* x3 x3) (* y3 y3)) (- y2 y1))))
         (c (+ (* (+ (* x1 x1) (* y1 y1)) (- x2 x3))
               (* (+ (* x2 x2) (* y2 y2)) (- x3 x1))
               (* (+ (* x3 x3) (* y3 y3)) (- x1 x2)))))
    (handler-bind ((error (lambda (c)
                            (declare (ignore c))
                            (return-from calc-circumcenter nil))))
      (complex (- (/ b (* 2 a)))
               (- (/ c (* 2 a)))))))

(defun mini-disc-with-2-points (points end q1 q2 eps)
  "Returns the smallest circle that contains points, q1 and q2 (contains q1 and
q2 at the perimeter)."
  (declare (complex q1 q2)
           (double-float eps)
           ((integer 0 #.most-positive-fixnum) end))
  (let* ((center (* 1/2 (+ q1 q2)))
         (radius (abs (- q1 center))))
    (declare (complex center)
             (double-float radius))
    (dotimes (i end)
      (let ((new-point (aref points i)))
        (declare (complex new-point))
        (when (>= (abs (- new-point center)) (+ radius eps))
          (let ((new-center (calc-circumcenter q1 q2 new-point)))
            (setq center new-center
                  radius (abs (- new-point new-center)))))))
    (values center radius)))

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

(defun mini-disc-with-point (points end q eps)
  (declare (complex q)
           (double-float eps))
  (%shuffle! points end)
  (let* ((center (* 1/2 (+ (aref points 0) q)))
         (radius (abs (- q center))))
    (declare (complex center)
             (double-float radius))
    (loop for i from 1 below end
          for new-point of-type complex = (aref points i)
          when (>= (abs (- new-point center)) (+ radius eps))
          do (setf (values center radius)
                   (mini-disc-with-2-points points i (aref points i) q eps)))
    (values center radius)))

(defun calc-smallest-circle (points eps)
  (assert (>= (length points) 1))
  (when (= 1 (length points))
    (return-from calc-smallest-circle
      (values (aref points 0)
              (coerce 0 (type-of (realpart (aref points 0)))))))
  (let* ((points (copy-seq points))
         (copy (copy-seq points))
         (p0 (aref points 0))
         (p1 (aref points 1))
         (center (* 1/2 (+ p0 p1)))
         (radius (abs (- p0 center))))
    (%shuffle! points)
    (loop for i from 2 below (length points)
          for new-point = (aref points i)
          when (>= (abs (- new-point center)) (+ radius eps))
          do (setf (values center radius)
                   (mini-disc-with-point copy i new-point eps)))
    (values center radius)))

(defun main ()
  (let* ((n (read))
         (points (make-array n :element-type '(complex double-float))))
    (declare (uint16 n))
    (dotimes (i n)
      (let ((x (float (read) 1d0))
            (y (float (read) 1d0)))
        (setf (aref points i) (complex x y))))
    (println (nth-value 1 (calc-smallest-circle points 1d-9)))))

#-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 "2
0 0
1 0
"
    "0.500000000000000000
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
0 0
0 1
1 0
"
    "0.707106781186497524
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10
10 9
5 9
2 0
0 0
2 7
3 3
2 5
10 0
3 7
1 9
"
    "6.726812023536805158
")))

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.


(defun solve (n playlist x)
  (declare (ignore n))
  (loop for ((title . s) . rest) on playlist
        if (string= title x)
        do (return
             (loop for (nil . time) in rest
                   summing time))))

#-swank
(let* ((n (read))
       (playlist (loop repeat n
                       for line = (read-line)
                       for pos = (position #\Space line)
                       collect (cons (subseq line 0 pos)
                                     (parse-integer line :start (1+ pos)))))
       (x (read-line)))
  (format t "~A~%" (solve n playlist x)))

Score : 200 points

Problem Statement

Niwango created a playlist of N songs.
The title and the duration of the i-th song are s_i and t_i seconds, respectively.
It is guaranteed that s_1,\ldots,s_N are all distinct.

Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, without any pause in between.)
However, he fell asleep during his work, and he woke up after all the songs were played.
According to his record, it turned out that he fell asleep at the very end of the song titled X.

Find the duration of time when some song was played while Niwango was asleep.

Constraints

1 \leq N \leq 50

s_i and X are strings of length between 1 and 100 (inclusive) consisting of lowercase English letters.

s_1,\ldots,s_N are distinct.

There exists an integer i such that s_i = X.

1 \leq t_i \leq 1000

t_i is an integer.

Input

Input is given from Standard Input in the following format:

N
s_1 t_1
\vdots
s_{N} t_N
X

Output

Print the answer.

Sample Input 1

3
dwango 2
sixth 5
prelims 25
dwango

Sample Output 1

30

While Niwango was asleep, two songs were played: sixth and prelims.

The answer is the total duration of these songs, 30.

Sample Input 2

1
abcde 1000
abcde

Sample Output 2

0

No songs were played while Niwango was asleep.

In such a case, the total duration of songs is 0.

Sample Input 3

15
ypnxn 279
kgjgwx 464
qquhuwq 327
rxing 549
pmuduhznoaqu 832
dagktgdarveusju 595
wunfagppcoi 200
dhavrncwfw 720
jpcmigg 658
wrczqxycivdqn 639
mcmkkbnjfeod 992
htqvkgkbhtytsz 130
twflegsjz 467
dswxxrxuzzfhkp 989
szfwtzfpnscgue 958
pmuduhznoaqu

Sample Output 3

6348


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

(defun fact (n)
  (if (= n 1)
      1
      (* n (fact (1- n)))))

(defparameter N (parse-integer (read-line)))
(defparameter lst
  (mapcar #'parse-integer (split " " (read-line))))
(defparameter const (+ 7 (expt 10 9)))
(defparameter dists
  (loop for i from 0 below (1- N)
        collect (- (nth (1+ i) lst) (nth i lst))))
(defparameter f (fact (1- N)))
(defparameter coeff
  (loop for i from 1 below N
        collect (apply #'+
                       (loop for j from 1 to i
                             collect (/ 1 j)))))

(format t "~A" (mod (* f (add-lst coeff dists)) const))

Score : 600 points

Problem Statement

There are N slimes standing on a number line.
The i-th slime from the left is at position x_i.

It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}.

Niwango will perform N-1 operations. The i-th operation consists of the following procedures:

Choose an integer k between 1 and N-i (inclusive) with equal probability.

Move the k-th slime from the left, to the position of the neighboring slime to the right.

Fuse the two slimes at the same position into one slime.

Find the total distance traveled by the slimes multiplied by (N-1)! (we can show that this value is an integer), modulo (10^{9}+7). If a slime is born by a fuse and that slime moves, we count it as just one slime.

Constraints

2 \leq N \leq 10^{5}

1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}

x_i is an integer.

Subtasks

400 points will be awarded for passing the test cases satisfying N \leq 2000.

Input

Input is given from Standard Input in the following format:

N
x_1 x_2 \ldots x_N

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

5

With probability \frac{1}{2}, the leftmost slime is chosen in the first operation, in which case the total distance traveled is 2.

With probability \frac{1}{2}, the middle slime is chosen in the first operation, in which case the total distance traveled is 3.

The answer is the expected total distance traveled, 2.5, multiplied by 2!, which is 5.

Sample Input 2

12
161735902 211047202 430302156 450968417 628894325 707723857 731963982 822804784 880895728 923078537 971407775 982631932

Sample Output 2

750927044

Find the expected value multiplied by (N-1)!, modulo (10^9+7).


(let ((n (read))
      (v (read)))
  (if (<= v (* n 500))
      (princ "Yes")
      (princ "No")))

Score : 100 points

Problem Statement

Takahashi has K 500-yen coins. (Yen is the currency of Japan.)
If these coins add up to X yen or more, print Yes; otherwise, print No.

Constraints

1 \leq K \leq 100

1 \leq X \leq 10^5

Input

Input is given from Standard Input in the following format:

K X

Output

If the coins add up to X yen or more, print Yes; otherwise, print No.

Sample Input 1

2 900

Sample Output 1

Yes

Two 500-yen coins add up to 1000 yen, which is not less than X = 900 yen.

Sample Input 2

1 501

Sample Output 2

No

One 500-yen coin is worth 500 yen, which is less than X = 501 yen.

Sample Input 3

4 2000

Sample Output 3

Yes

Four 500-yen coins add up to 2000 yen, which is not less than X = 2000 yen.


(defun splitat (c line)
  (labels ((rec (line acc)
				(let ((pos (position-if (lambda(cc) (char= c cc)) line)))
				  (if pos
					  (rec (subseq line (1+ pos)) (cons (subseq line 0 pos) acc))
					(nreverse (cons line acc))))))
	(rec line nil)))
(defun f(k x)
  (<= x (* 500 k)))
(let* ((line (mapcar #'parse-integer (splitat #\space (read-line nil nil)))))
  (format t "~A~%" (if (f (car line) (cadr line)) "Yes" "No")))


(let* ((m (read))
       (n (read-line)))
  (princ (loop :for k :from 0 :upto (- (length n) 3) :count (string= "ABC" (subseq n k (+ k 3))))))

Score : 200 points

Problem Statement

We have a string S of length N consisting of uppercase English letters.

How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?

Constraints

3 \leq N \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print number of occurrences of ABC in S as contiguous subsequences.

Sample Input 1

10
ZABCDBABCQ

Sample Output 1

2

Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.

Sample Input 2

19
THREEONEFOURONEFIVE

Sample Output 2

0

No contiguous subsequences of S are equal to ABC.

Sample Input 3

33
ABCCABCBABCCABACBCBBABCBCBCBCABCB

Sample Output 3

5


(defun fact (n)
  (let ((fact 1))
    (loop :for i :from 2 :to n
          :do (setf fact (* i fact)))
    fact))

(defun permutaions (n)
  (let ((table (make-hash-table :size (fact n) :test 'equalp))
        (order 0))
    (labels ((next (n use vec)
               (if (= (length vec) n)
                   (setf (gethash (copy-seq vec) table) (incf order))
                   (loop :for i :from 1 :to n
                         :unless (aref use i)
                         :do (progn
                               (setf (aref use i) t)
                               (vector-push i vec)
                               (next n use vec)
                               (vector-pop vec)
                               (setf (aref use i) nil))))))
      (next n
            (make-array `(,(1+ n)) :initial-element nil)
            (make-array `(,n) :adjustable t :fill-pointer 0))
      table)))

(let* ((n (read))
       (p (make-array `(,n)))
       (q (make-array `(,n)))
       (m (permutaions n)))
  (loop :for i :from 0 :to (1- n)
        :do (setf (aref p i) (read)))
  (loop :for i :from 0 :to (1- n)
        :do (setf (aref q i) (read)))
  (format t "~A~%" (abs (- (gethash p m) (gethash q m)))))

Score : 300 points

Problem Statement

We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).

There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.

Notes

For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.

Sample Input 2

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

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0


(let* ((n (read))
       (a (loop :repeat n :collect (read)))
       (b (loop :repeat n :collect (read)))
       (pm (reverse (mapcar #'reverse (permutation (loop :for k :from 1 :upto n :collect k))))))
  (princ (abs (- (position a pm :test #'equal) (position b pm :test #'equal)))))


(defun split (input stack-string output-list)
  (let ((chara (car input)))
    (case chara
          ((nil) (append output-list (list stack-string)))
          (#\space (split (cdr input)
                          '()
                          (append output-list (list stack-string))))
          (otherwise (split (cdr input)
                            (concatenate 'string stack-string (list chara))
                            output-list)))))

(defun input-to-list (input)
  (mapcar #'parse-integer (split (concatenate 'list input)
                                 '()
                                 '())))

(defun fact (n)
  (labels ((inner (mem n)
                  (if (zerop n)
                      mem
                      (inner (* mem n) (1- n)))
                  ))
          (inner 1 n)))

(defun dec (lst n)
  (if lst
      (+ (* (fact (1- n)) (1- (car lst))) (dec (cdr lst) (1- n)))
      0))

(defvar n (parse-integer (read-line)))
(defvar p (input-to-list (read-line)))
(defvar q (input-to-list (read-line)))

(princ (abs (- (dec p n) (dec q n))))


(defun splitat (c line)
  (labels ((rec (line acc)
				(let ((pos (position-if (lambda(cc) (char= c cc)) line)))
				  (if pos
					  (rec (subseq line (1+ pos)) (cons (subseq line 0 pos) acc))
					(nreverse (cons line acc))))))
	(rec line nil)))
(defun lessp(a b)
  (labels ((rec(a b)
             (if (null a)
               nil
               (if (< (car a) (car b))
                 t
                 (if (= (car a) (car b))
                   (rec (cdr a) (cdr b))
                   nil)))))
    (rec a b)))
(defun flatten1(lst)
  (nreverse (reduce (lambda (acc a)
					  (reduce (lambda (acc a)
								(cons a acc))
							  a :initial-value acc))
					lst :initial-value nil)))
(defun permutations(lst)
  (labels ((skip(i n lst acc)
			 (cond ((null lst) acc)
				   ((= i n) (skip (1+ i) n (cdr lst) acc))
				   (t (skip (1+ i) n (cdr lst) (cons (car lst) acc)))))
		   (rec (lst acc acc0)
				(if (null lst)
				  (cons acc acc0)
				  (flatten1 (mapcar (lambda(i) (rec (nreverse (skip 0 i lst nil)) (cons (nth i lst) acc) acc0)) (loop for i from 0 to (1- (length lst)) collect i)))
				  ))
				)
	(rec lst nil nil)))
(defun equallst(a b)
  (labels ((rec(a b)
             (if (null a)
               t
               (if (= (car a) (car b))
                 (rec (cdr a) (cdr b))
                 nil))))
    (rec a b)))
(defun searcher (hystack needle)
  (labels ((rec(hystack i)
             (if (null hystack)
               -1
               (if (equallst (car hystack) needle)
                 i
                 (rec (cdr hystack) (1+ i))))))
    (rec hystack 0)))
(defun f(n p q)
  (let* ((pq (sort (permutations (loop for i from 1 to n collect i)) #'lessp))
         (pn (searcher pq p))
         (qn (searcher pq q)))
    (abs (- pn qn))))

(compile 'lessp)
(compile 'equallst)
(compile 'searcher)
(compile 'f)
(let* ((n (parse-integer (read-line nil nil)))
       (p (mapcar #'parse-integer (splitat #\space (read-line nil nil))))
       (q (mapcar #'parse-integer (splitat #\space (read-line nil nil)))))
  (format t "~A~%" (f n p q)))


;; D - Semi Common Multiple

(defun main ()
  (let* ((N (read))
         (M (read))
         (A (loop repeat N collect (read))))
    (princ (solve N M A))
    (fresh-line)))

(defun solve (N M A)
  (let* ((H (mapcar #'(lambda (x) (floor x 2)) A)) ; a_i / 2
         (lcm (loop for x in H
                    for l = x then (lcm l x) while (<= l M)
                    finally (return l)))) ; Hの最小公倍数
    (if (and (<= lcm M)
             (every #'(lambda (x) (oddp (floor lcm x))) H)) ; 全要素の奇数倍
        (ash (1+ (floor M lcm)) -1) ; M以下のlcmの奇数倍の個数
        0)))

(main)

Score : 400 points

Problem Statement

Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.

Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):

There exists a non-negative integer p such that X= a_k \times (p+0.5).

Find the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^9

2 \leq a_i \leq 10^9

a_i is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 a_2 ... a_N

Output

Print the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Sample Input 1

2 50
6 10

Sample Output 1

2

15 = 6 \times 2.5

15 = 10 \times 1.5

45 = 6 \times 7.5

45 = 10 \times 4.5

Thus, 15 and 45 are semi-common multiples of A. There are no other semi-common multiples of A between 1 and 50, so the answer is 2.

Sample Input 2

3 100
14 22 40

Sample Output 2

0

The answer can be 0.

Sample Input 3

5 1000000000
6 6 2 6 2

Sample Output 3

166666667


(defun solve (n m a)
  (let ((lcm (apply #'lcm
                    (mapcar (lambda (x)
                              (multiple-value-bind (quotient remainder)
                                  (truncate x 2)
                                (if (zerop remainder)
                                    quotient
                                    (return-from solve 0))))
                            a))))
    (ceiling (floor m lcm) 2)))

#-swank
(let* ((n (read))
       (m (read))
       (a (loop repeat n collect (read))))
  (format t "~A~%" (solve n m a)))


(defun solve (n m a)
  (let ((lcm (apply #'lcm
                    (mapcar (lambda (a) (/ a 2))
                            a))))
    (ceiling (floor m lcm) 2)))

#-swank
(let* ((n (read))
       (m (read))
       (a (loop repeat n collect (read))))
  (format t "~A~%" (solve n m a)))


(map 'list #'(lambda (c) (unless (eq c #\space) (princ c))) (read-line))

Score : 100 points

Problem Statement

Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.

Constraints

S and T are strings consisting of lowercase English letters.

The lengths of S and T are between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S T

Output

Print the resulting string.

Sample Input 1

oder atc

Sample Output 1

atcoder

When S = oder and T = atc, concatenating T and S in this order results in atcoder.

Sample Input 2

humu humu

Sample Output 2

humuhumu


(defun is-prime(x i)
  (if (= x 1)
	nil
	(if (= x 2)
	  t
	  (if (zerop (mod x i))
		nil
		(if (<= (* i i) x)
		  (is-prime x (1+ i))
		  t)))))

(defun func(x)
  (if (is-prime x 2)
	x
	(func (1+ x))))

(let ((x (read)))
  (princ (func x)))

Score: 300 points

Problem Statement

Find the minimum prime number greater than or equal to X.

Notes

A prime number is an integer greater than 1 that cannot be evenly divided by any positive integer except 1 and itself.

For example, 2, 3, and 5 are prime numbers, while 4 and 6 are not.

Constraints

2 \le X \le 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the minimum prime number greater than or equal to X.

Sample Input 1

20

Sample Output 1

23

The minimum prime number greater than or equal to 20 is 23.

Sample Input 2

2

Sample Output 2

2

X itself can be a prime number.

Sample Input 3

99992

Sample Output 3

100003


(let* ((n (read))
       (k (read))
       (r (read))
       (s (read))
       (p (read))
       (x (read-line))
       (y (make-array (list (1+ n)) :initial-element #\x))
       (ans 0))
  (loop :for i :from 1 :to k
        :for h := (aref x (1- i))
        :do (cond ((char= h #\r)
                   (incf ans p)
                   (setf (aref y i) #\r))
                  ((char= h #\s)
                   (incf ans r)
                   (setf (aref y i) #\s))
                  ((char= h #\p)
                   (incf ans s)
                   (setf (aref y i) #\p))))
  (loop :for i :from (1+ k) :to n
        :for h := (aref x (1- i))
        :if (char/= (aref y (- i k)) h)
        :do (cond ((char= h #\r)
                   (incf ans p)
                   (setf (aref y i) #\r))
                  ((char= h #\s)
                   (incf ans r)
                   (setf (aref y i) #\s))
                  ((char= h #\p)
                   (incf ans s)
                   (setf (aref y i) #\p))))
  (format t "~A~%" ans))

Score : 400 points

Problem Statement

At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:

The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)

Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):

R points for winning with Rock;

S points for winning with Scissors;

P points for winning with Paper.

However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)

Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.

The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.

What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

Notes

In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.

If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;

if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;

if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;

if both players play the same hand, it is a draw.

Constraints

2 \leq N \leq 10^5

1 \leq K \leq N-1

1 \leq R,S,P \leq 10^4

N,K,R,S, and P are all integers.

|T| = N

T consists of r, p, and s.

Input

Input is given from Standard Input in the following format:

N K
R S P
T

Output

Print the maximum total score earned in the game.

Sample Input 1

5 2
8 7 6
rsrpr

Sample Output 1

27

The machine will play {Rock, Scissors, Rock, Paper, Rock}.

We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn 27 points.
We cannot earn more points, so the answer is 27.

Sample Input 2

7 1
100 10 1
ssssppr

Sample Output 2

211

Sample Input 3

30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr

Sample Output 3

4996


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

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

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

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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT
           (inline sort))
  (let* ((n (read))
         (m (read))
         (as (make-array n :element-type 'uint31)))
    (declare ((simple-array uint31 (*)) as))
    (dotimes  (i n)
      (let ((a (read-fixnum)))
        (setf (aref as i) a)))
    (setq as (sort as #'>))
    (let ((cumuls (make-array (+ n 1) :element-type 'uint62)))
      (dotimes (i n)
        (setf (aref cumuls (+ i 1))
              (+ (aref as i) (aref cumuls i))))
      (labels ((%calc-sum (pivot threshold)
                 (declare (uint62 pivot threshold))
                 (let ((sup (bisect-right as
                                          (- threshold (aref as pivot))
                                          :order #'>)))
                   (+ (the uint62 (* sup (aref as pivot)))
                      (aref cumuls sup))))
               (calc-sum (threshold)
                 (loop for i below n
                       sum (%calc-sum i threshold) of-type uint62))
               (%calc-count (pivot threshold)
                 (declare (uint62 pivot threshold))
                 (let ((sup (bisect-right as
                                          (- threshold (aref as pivot))
                                          :order #'>)))
                   sup))
               (calc-count (threshold)
                 (loop for i below n
                       sum (%calc-count i threshold) of-type uint62)))
        (sb-int:named-let bisect ((ok -1) (ng 10000000))
          (declare (int32 ng ok))
          (if (<= (- ng ok) 1)
              (let ((actual-count (calc-count ok))
                    (sum (calc-sum ok)))
                (assert (>= actual-count m))
                (println
                 (- sum (* (- actual-count m) ok))))
              (let ((mid (ash (+ ng ok) -1)))
                (if (>= (calc-count mid) m)
                    (bisect mid ng)
                    (bisect ok mid)))))))))

#-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 "5 3
10 14 19 34 33
"
    "202
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "9 14
1 3 5 110 24 21 34 5 3
"
    "1837
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "9 73
67597 52981 5828 66249 75177 64141 40773 79105 16076
"
    "8128170
")))

Score : 500 points

Problem Statement

Takahashi has come to a party as a special guest.
There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.

Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0).
A handshake will be performed as follows:

Takahashi chooses one (ordinary) guest x for his left hand and another guest y for his right hand (x and y can be the same).

Then, he shakes the left hand of Guest x and the right hand of Guest y simultaneously to increase the happiness by A_x+A_y.

However, Takahashi should not perform the same handshake more than once. Formally, the following condition must hold:

Assume that, in the k-th handshake, Takahashi shakes the left hand of Guest x_k and the right hand of Guest y_k. Then, there is no pair p, q (1 \leq p < q \leq M) such that (x_p,y_p)=(x_q,y_q).

What is the maximum possible happiness after M handshakes?

Constraints

1 \leq N \leq 10^5

1 \leq M \leq N^2

1 \leq A_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the maximum possible happiness after M handshakes.

Sample Input 1

5 3
10 14 19 34 33

Sample Output 1

202

Let us say that Takahashi performs the following handshakes:

In the first handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 4.

In the second handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 5.

In the third handshake, Takahashi shakes the left hand of Guest 5 and the right hand of Guest 4.

Then, we will have the happiness of (34+34)+(34+33)+(33+34)=202.

We cannot achieve the happiness of 203 or greater, so the answer is 202.

Sample Input 2

9 14
1 3 5 110 24 21 34 5 3

Sample Output 2

1837

Sample Input 3

9 73
67597 52981 5828 66249 75177 64141 40773 79105 16076

Sample Output 3

8128170


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

#-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 "5 3
10 14 19 34 33
"
    "202
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "9 14
1 3 5 110 24 21 34 5 3
"
    "1837
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "9 73
67597 52981 5828 66249 75177 64141 40773 79105 16076
"
    "8128170
")))


;; F - Surrounded Nodes

(defparameter *modulus* (+ (expt 10 9) 7))

(defun main ()
  (let* ((N (read))  ; 頂点数
         (tree (read-tree N)))
    (princ (solve N tree))
    (fresh-line)))

; (a) 自分が白 かつ (b) 隣接する部分グラフの2つ以上に黒が含まれる
; ならば, 自分はSに含まれる白頂点.
; 塗り分け方すべて: 2^N
; 自分が白: 2^(N - 1)
; (b) == not ((b1) or (b2))
; (b1) 隣接する部分グラフがすべて白: 1
; (b2) 隣接する部分グラフのちょうど一つGに黒が含まれる: 2^size(G) - 1
; 自分がSに含まれる白頂点である確率:
; (2^(N - 1) - 1 - sum_G (2^size(G) - 1))/2^N
; 全頂点の合計:
; (N * 2^(N - 1) - N - (sum_G 2^size(G)) + 2 * (N - 1))/2^N

(defun solve (N tree)
  (destructuring-bind
    ; 各頂点の親と各部分木の頂点数
    (parent subtree-size) (make-rooted-tree 0 tree)
    (let* ((subgraph-size ; 部分グラフの頂点数のリスト
             (loop for v below N append ; 各頂点
               (loop for next in (aref tree v) collect ; vの隣接頂点
                 ; nextの向こう側の部分グラフの頂点数
                 (if (eql next (aref parent v)) ; vの親?
                     (- N (aref subtree-size v))
                     (aref subtree-size next)))))
           (numerator (- (* N (1+ (ash 1 (1- N))))
                         (reduce #'+
                           (mapcar #'mod-expt-2
                             (normalize-exponents subgraph-size)))
                         2)))
    ; (2^N) * z == numerator mod *modulus* であるz
    ; *modulus*が素数なので 2^(*modulus* - 1) == 1 mod *modulus*
    (mod (* (mod numerator *modulus*) (mod-expt-2 (- *modulus* 1 N)))
         *modulus*))))

; 2, 2^100, 2^10000, 2^1000000 (mod *modulus*) のリスト
(defparameter *expt-2*
  (loop for n = 1 then (* n 100) while (< n *modulus*)
        collect (mod (ash 1 n) *modulus*)))

(defun mod-expt-2 (i)
  "(mod (expt 2 i) *modulus*)を少し速く計算"
  (mod (reduce #'*
         (loop for n = 1 then (* n 100)
               for x = i then (floor x 100) while (plusp x)
               for e in *expt-2*
               collect (expt e (mod x 100))))
       *modulus*))

(defun normalize-exponents (lst)
  "2の指数のリストを正規化"
  (setf lst (sort lst #'<))
  (labels ((normalizer (head n lst result)
             (cond ((and lst (eql (car lst) head))
                    (normalizer head (1+ n) (cdr lst) result))
                   ((>= n 2)
                    (normalizer (1+ head) (ash n -1) lst
                      (if (oddp n) (cons head result) result)))
                   (lst
                    (normalizer (car lst) 1 (cdr lst) (cons head result)))
                   (t (cons head result)))))
    (normalizer (car lst) 1 (cdr lst) ())))

(defun make-rooted-tree (root tree)
  "頂点rootを根としてtreeの各頂点の親を決める. 部分木の大きさも計算する."
  (let* ((N (array-dimension tree 0)) ; 頂点数
         (parent (make-array N :initial-element nil)) ; 親
         (subtree-size (make-array N :initial-element nil))) ; 部分木の頂点数
    (labels
      ((dfs (stack)
         (when stack
           (let ((v (pop stack)))
             (if (aref subtree-size v)
               ; 帰りがけ
               (loop for next in (aref tree v) ; vの隣接頂点
                 unless (eql next (aref parent v)) ; 親以外
                   do (incf (aref subtree-size v)
                            (aref subtree-size next)))
               ; 行きがけ
               (loop
                 initially (push v stack) ; 帰りがけ用に残す
                           (setf (aref subtree-size v) 1)
                 for next in (aref tree v) ; vの隣接頂点
                 unless (eql next (aref parent v)) ; 親以外
                   do (push next stack)
                      (setf (aref parent next) v))))
           (dfs stack))))
      (dfs (list root))
      (list parent subtree-size))))

(defun read-tree (N)
  "N頂点の木をreadして作る. 頂点番号は0〜N-1"
  (let ((tree (make-array N))) ; 隣接リスト
    (loop for i below N do (setf (aref tree i) nil))
    (loop repeat (1- N)
      do (let ((a (read-fixnum))
               (b (read-fixnum)))
           (push (1- b) (aref tree (1- a)))
           (push (1- a) (aref tree (1- b)))))
    tree))

(defun read-fixnum (&optional (in *standard-input*))
  "readより速い整数専用read.
   参考: 競技プログラミングでCommon Lispを使っている人と
   これから使うかもしれない人のために, @sansaqua
   https://qiita.com/sansaqua/items/0b6417cb541047e29da4"
  (loop with acc = 0
        with minus = nil
        with started = nil
        for byte = (read-byte in)
        if (<= 48 byte 57)
          do (setf acc (+ (* acc 10) (- byte 48)))
             (setf started t)
        else if started
          return (if minus (- acc) acc)
        else if (= byte 45)
          do (setf minus t)))

(main)

Score : 600 points

Problem Statement

Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).

Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all the vertices painted black. (If no vertex is painted black, S is the empty graph.)

Let the holeyness of S be the number of white vertices contained in S. Find the expected holeyness of S.

Since the answer is a rational number, we ask you to print it \bmod 10^9+7, as described in Notes.

Notes

When you print a rational number, first write it as a fraction \frac{y}{x}, where x, y are integers, and x is not divisible by 10^9 + 7
(under the constraints of the problem, such representation is always possible).

Then, you need to print the only integer z between 0 and 10^9 + 6, inclusive, that satisfies xz \equiv y \pmod{10^9 + 7}.

Constraints

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

1 \leq A_i,B_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_{N-1} B_{N-1}

Output

Print the expected holeyness of S, \bmod 10^9+7.

Sample Input 1

3
1 2
2 3

Sample Output 1

125000001

If the vertices 1, 2, 3 are painted black, white, black, respectively, the holeyness of S is 1.

Otherwise, the holeyness is 0, so the expected holeyness is 1/8.

Since 8 \times 125000001 \equiv 1 \pmod{10^9+7}, we should print 125000001.

Sample Input 2

4
1 2
2 3
3 4

Sample Output 2

375000003

The expected holeyness is 3/8.

Since 8 \times 375000003 \equiv 3 \pmod{10^9+7}, we should print 375000003.

Sample Input 3

4
1 2
1 3
1 4

Sample Output 3

250000002

The expected holeyness is 1/4.

Sample Input 4

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

Sample Output 4

570312505


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

#-swank (main)

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

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

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

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

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

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

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

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

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


(defun table-tennis-training ()
  (let ((n (read))
        (a (read))
        (b (read))
        (ans 0))
    (if (evenp (- b a))
        (setf ans (/ (- b a) 2))
        (if (< (- a 1) (- n b))
            (setf ans (- b 1))
            (setf ans (- n a))))
    ans))

(format t "~d~%" (table-tennis-training))

Score : 300 points

Problem Statement

2N players are running a competitive table tennis training on N tables numbered from 1 to N.

The training consists of rounds.
In each round, the players form N pairs, one pair per table.
In each pair, competitors play a match against each other.
As a result, one of them wins and the other one loses.

The winner of the match on table X plays on table X-1 in the next round,
except for the winner of the match on table 1 who stays at table 1.

Similarly, the loser of the match on table X plays on table X+1 in the next round,
except for the loser of the match on table N who stays at table N.

Two friends are playing their first round matches on distinct tables A and B.
Let's assume that the friends are strong enough to win or lose any match at will.
What is the smallest number of rounds after which the friends can get to play a match against each other?

Constraints

2 \leq N \leq 10^{18}

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the smallest number of rounds after which the friends can get to play a match against each other.

Sample Input 1

5 2 4

Sample Output 1

1

If the first friend loses their match and the second friend wins their match, they will both move to table 3 and play each other in the next round.

Sample Input 2

5 2 3

Sample Output 2

2

If both friends win two matches in a row, they will both move to table 1.


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

(defparameter lst (mapcar #'parse-integer (split " " (read-line))))
(defparameter N (car lst))
(defparameter A (cadr lst))
(defparameter B (caddr lst))

(if (oddp (- A B))
    (format t "~A" (min (1- (max A B)) (- N (min A B))))
    (format t "~A" (floor (abs (/ (- A B) 2)))))


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

(defparameter lst (mapcar #'parse-integer (split " " (read-line))))
(defparameter N (car lst))
(defparameter A (cadr lst))
(defparameter B (caddr lst))

(if (oddp (- A B))
    (format t "~A" (apply #'min (list (1- (apply #'max (list A B)))
                                      (- N (apply #'min (list A B))))))
    (format t "~A" (floot (abs (/ (- A B) 2)))))


(defun solve (n a b)
  (let ((diff (abs (- a b))))
    (if (zerop (rem diff 2))
        (floor diff 2)
        (if (< a b)
          (min (- n a) (- b 1))
          (min (- n b) (- a 1))))))

(let ((n (read))
      (a (read))
      (b (read)))
  (format t "~A~%" (solve n a b)))


(let ((ans (make-array '(4) :initial-element t)))
  (setf (aref ans (read)) nil)
  (setf (aref ans (read)) nil)
  (loop :for i :from 1 :to 3
        :if (aref ans i)
        :return (format t "~A~%" i)))

Score: 100 points

Problem Statement

Takahashi is solving quizzes. He has easily solved all but the last one.

The last quiz has three choices: 1, 2, and 3.

With his supernatural power, Takahashi has found out that the choices A and B are both wrong.

Print the correct choice for this problem.

Constraints

Each of the numbers A and B is 1, 2, or 3.

A and B are different.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print the correct choice.

Sample Input 1

3
1

Sample Output 1

2

When we know 3 and 1 are both wrong, the correct choice is 2.

Sample Input 2

1
2

Sample Output 2

3


(defun gen (str1 str2 &optional s)
  (cond ((equal str1 "") s)
    (t (gen (subseq str1 1) (subseq str2 1)
       (concatenate 'string s (subseq str1 0 1)(subseq str2 0 1)))))
  )

(let* ((n (read))
       (s (read-line))
       (str1 (subseq s 0 n))
       (str2 (subseq s (+ n 1))))
      (format t "~A~%" (gen str1 str2)))


(defun solve (a b)
  (first
    (remove-if (lambda (x)
                 (or (= x a)
                     (= x b)))
               '(1 2 3))))

#-swank
(let ((a (read))
      (b (read)))
  (format t "~A~%" (solve a b)))


;; B - Strings with the Same Length

(defun main ()
  (let* ((N (read))
         (row (read-line))
         (SS (subseq row 0 N))
         (ST (subseq row (1+ N))))
    (princ (interleave SS ST))))

(defun interleave (s1 s2)
  (apply #'concatenate 'string
    (mapcar #'(lambda (ls) (coerce ls 'string))
      (map 'list #'list s1 s2))))

(main)

Score : 200 points

Problem Statement

Given are strings s and t of length N each, both consisting of lowercase English letters.

Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.

Constraints

1 \leq N \leq 100

|S| = |T| = N

S and T are strings consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S T

Output

Print the string formed.

Sample Input 1

2
ip cc

Sample Output 1

icpc

Sample Input 2

8
hmhmnknk uuuuuuuu

Sample Output 2

humuhumunukunuku

Sample Input 3

5
aaaaa aaaaa

Sample Output 3

aaaaaaaaaa


(let* ((n (read))
       (str (read-line))
       (ans nil))
  (map nil (lambda (j k)
             (push j ans)
             (push k ans)) str (subseq str (+ 1 n)))
  (princ (concatenate 'string (reverse ans))))


(defun splitat (c line)
  (labels ((rec (line acc)
				(let ((pos (position-if (lambda(cc) (char= c cc)) line)))
				  (if pos
					  (rec (subseq line (1+ pos)) (cons (subseq line 0 pos) acc))
					(nreverse (cons line acc))))))
	(rec line nil)))
(defun f(str0 str1)
  (labels ((rec(i acc)
             (if (< i (length str0))
               (rec (1+ i) (cons (char str1 i) (cons (char str0 i) acc)))
               (nreverse acc))))
    (rec 0 nil)))
(let* ((line0 (read-line nil nil))
       (line1 (read-line nil nil))
       (splited (splitat #\space line1)))
  (format t "~{~A~}~%" (f (car splited) (cadr splited))))


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

(defparameter lst (mapcar #'parse-integer (split " " (read-line))))

(format t "~A" (lcm (car lst) (cadr lst)))

Score : 300 points

Problem Statement

Takahashi is organizing a party.

At the party, each guest will receive one or more snack pieces.

Takahashi predicts that the number of guests at this party will be A or B.

Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted.

We assume that a piece cannot be divided and distributed to multiple guests.

Constraints

1 \leq A, B \leq 10^5

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of pieces that can be evenly distributed to the guests in both of the cases with A guests and B guests.

Sample Input 1

2 3

Sample Output 1

6

When we have six snack pieces, each guest can take three pieces if we have two guests, and each guest can take two if we have three guests.

Sample Input 2

123 456

Sample Output 2

18696

Sample Input 3

100000 99999

Sample Output 3

9999900000


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

(defun solve-2 (n i bricks start)
  (let ((next (position i bricks :start start :test #'=)))
    (if next
        (+ (- next start) (solve-2 n (1+ i) bricks (1+ next)))
        (- n start))))

(defun solve (n bricks)
  (let ((res (solve-2 n 1 bricks 0)))
    (if (= n res)
        -1
        res)))

#-swank
(let* ((n (read))
       (bricks (make-array n :element-type 'integer)))
  (loop for i from 0 below n
        do (setf (aref bricks i) (read)))
  (format t "~A~%" (solve n bricks)))

Score : 400 points

Problem Statement

We have N bricks arranged in a row from left to right.

The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.

Among them, you can break at most N-1 bricks of your choice.

Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of those brick from the left has the integer i written on it.

Find the minimum number of bricks you need to break to satisfy Snuke's desire. If his desire is unsatisfiable, print -1 instead.

Constraints

All values in input are integers.

1 \leq N \leq 200000

1 \leq a_i \leq N

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of bricks that need to be broken to satisfy Snuke's desire, or print -1 if his desire is unsatisfiable.

Sample Input 1

3
2 1 2

Sample Output 1

1

If we break the leftmost brick, the remaining bricks have integers 1 and 2 written on them from left to right, in which case Snuke will be satisfied.

Sample Input 2

3
2 2 2

Sample Output 2

-1

In this case, there is no way to break some of the bricks to satisfy Snuke's desire.

Sample Input 3

10
3 1 4 1 5 9 2 6 5 3

Sample Output 3

7

Sample Input 4

1
1

Sample Output 4

0

There may be no need to break the bricks at all.


(defun solve-2 (n i bricks start)
  (let ((next (position i bricks :start start :test #'=)))
    (if next
        (+ (- next start) (solve-2 n (1+ i) bricks (1+ next)))
        (- n start))))

(defun solve (n bricks)
  (let ((res (solve-2 n 1 bricks 0)))
    (if (= n res)
        -1
        res)))

#-swank
(let* ((n (read))
       (bricks (make-array n :element-type 'integer)))
  (loop for i from 0 below n
        do (setf (aref bricks i) (read)))
  (format t "~A~%" (solve n bricks)))


(defun func(n x)
  (if (> n 0)
	(if (eq (1+ x) (read))
	  (func (1- n) (1+ x))
	  (func (1- n) x))
	x))

(let* ((n (read)) (s (func n 0)))
  (princ (if (eq s 0) -1 (- n s))))


(defun check-bits (n bits bricks)
  (loop with i = 0
        for j from 0
        for bitidx from (1- n) downto 0
        unless (logbitp bitidx bits)
        do (progn
             (incf i)
             (unless (= i (aref bricks j))
               (return nil)))
        finally (return t)))

(defun solve (n bricks)
  (loop with ok = nil
        for bits from 0 below (1- (expt 2 n))
        if (check-bits n bits bricks)
        minimize (progn (setf ok t)
                        (logcount bits)) into result
        finally
        (return (if ok result -1))))

#-swank
(let* ((n (read))
       (bricks (make-array n :element-type 'integer)))
  (loop for i from 0 below n
        do (setf (aref bricks i) (read)))
  (format t "~A~%" (solve n bricks)))


;; -*- 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*))
  (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))
         (as (make-array n :element-type 'uint32))
         (len 0)
         (current-pos 0))
    (dotimes (i n)
      (setf (aref as i) (- (read-fixnum) 1)))
    (dotimes (i n)
      (let ((next-pos (position i as :start current-pos)))
        (unless next-pos
          (if (zerop i)
              (println -1)
              (println (- n i)))
          (return-from main))
        (setq current-pos next-pos)))
    (println 0)))

#-swank (main)

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

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

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

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

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

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

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

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

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


(defparameter m (read-line))
(defparameter N (parse-integer m))

(defun count-zero (n)
  (let* ((order (floor (log n 10)))
         (lst (loop for i from 0 to (+ 10 order)
                    collect (floor (/ n (* 10 (expt 5 i)))))))
        (apply #'+ lst)))

(defparameter answer
  (if (oddp N)
      0
      (count-zero N)))

(format t "~A" answer)

Score : 500 points

Problem Statement

For an integer n not less than 0, let us define f(n) as follows:

f(n) = 1 (if n < 2)

f(n) = n f(n-2) (if n \geq 2)

Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).

Constraints

0 \leq N \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of trailing zeros in the decimal notation of f(N).

Sample Input 1

12

Sample Output 1

1

f(12) = 12 × 10 × 8 × 6 × 4 × 2 = 46080, which has one trailing zero.

Sample Input 2

5

Sample Output 2

0

f(5) = 5 × 3 × 1 = 15, which has no trailing zeros.

Sample Input 3

1000000000000000000

Sample Output 3

124999999999999995


(let ((a (read-from-string (concatenate 'string "(" (read-line) ")"))))
     (if (<= (reduce #'+ a) 21)
         (princ "win")
         (princ "bust")))

Score : 100 points

Problem Statement

Given are three integers A_1, A_2, and A_3.

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Constraints

1 \leq A_i \leq 13 \ \ (i=1,2,3)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Sample Input 1

5 7 9

Sample Output 1

win

5+7+9=21, so print win.

Sample Input 2

13 7 2

Sample Output 2

bust

13+7+2=22, so print bust.


(let*(
    (cards (list (read) (read) (read)))
    (sum (reduce (lambda (m x) (+ m x)) cards)))
  (princ cards)
  (princ sum)
  (if
    (< sum 22)
    (princ "win")
    (princ "bust")))


(defun splitat (c line)
  (labels ((rec (line acc)
				(let ((pos (position-if (lambda(cc) (char= c cc)) line)))
				  (if pos
					  (rec (subseq line (1+ pos)) (cons (subseq line 0 pos) acc))
					(nreverse (cons line acc))))))
	(rec line nil)))

(defun f(line)
  (let ((lst (mapcar #'parse-integer (splitat #\space line))))
    (<= (reduce #'+ lst) 21)))
(let ((line (read-line nil nil)))
  (format t "~A~%" (if (f line) "win" "bust")))


(defun main ()
  (let* ((str (read-line))
        (buff)
        (n (length str)))
    (dotimes (i (/ n 2))
      (setf buff (subseq str i (1+ i)))
      (if (/= buff (subseq str (- n 2 i) (- n 1 i)))
          (setf (subseq str (- n 2 i) (- n 1 i)) buff)))
    str))

(main)

Score : 200 points

Problem Statement

Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.

Given is a string S. Find the minimum number of hugs needed to make S palindromic.

Constraints

S is a string consisting of lowercase English letters.

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

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of hugs needed to make S palindromic.

Sample Input 1

redcoder

Sample Output 1

1

For example, we can change the fourth character to o and get a palindrome redooder.

Sample Input 2

vvvvvv

Sample Output 2

0

We might need no hugs at all.

Sample Input 3

abcdabc

Sample Output 3

2


(defparameter data (read-line))

(let ((count 0))
     (loop for i from 0 below (/ (length data) 2) do
           (if (not (eq (char data i)
                        (char data (- (length data) i 1))))
               (incf count)))
     (format t "~A" count))


(defun make-init-array (i n)
  (let ((result (make-array n :initial-element -1)))
    (setf (aref result i) 1)
    result))

(defun solve-1 (i n infos array)
  (if (= (aref array i) -1)
      (let ((array2 (copy-seq array)))
        (setf (aref array2 i) 1)
        (handler-case (progn (solve-1 i n infos array2)
                             (setf array array2))
          (error () (setf (aref array i) 0))))
      (let ((honestp (= (aref array i) 1))
            (says (nth i infos)))
        (loop for (x . y) in says
              do (cond
                   ((= (aref array (1- x)) -1)
                    (setf (aref array (1- x))
                          (if honestp
                              y
                              (if (= y 0) 1 0)))
                    (solve-1 (1- x) n infos array))
                   ((= (aref array (1- x)) (if honestp y (if (= y 0) 1 0))))
                   (t
                    (error "Conflict"))))))
  (let ((next (position-if (lambda (x) (= x -1)) array)))
    (if next
        (solve-1 next n infos array)
        array)))

(defun solve (n infos)
  (loop for i from 0 below n
        for result = (handler-case (solve-1 i n infos (make-init-array i n))
                       (error () nil))
        maximize (if result
                     (count 1 result :test #'=)
                     0)))

#-swank
(let* ((n (read))
       (infos (loop repeat n
                    collect (let ((m (read)))
                              (loop repeat m
                                    collect (cons (read) (read)))))))
  (format t "~S~%" (solve n infos)))

Score : 300 points

Problem Statement

There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.

Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.

How many honest persons can be among those N people at most?

Constraints

All values in input are integers.

1 \leq N \leq 15

0 \leq A_i \leq N - 1

1 \leq x_{ij} \leq N

x_{ij} \neq i

x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)

y_{ij} = 0, 1

Input

Input is given from Standard Input in the following format:

N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}

Output

Print the maximum possible number of honest persons among the N people.

Sample Input 1

3
1
2 1
1
1 1
1
2 0

Sample Output 1

2

If Person 1 and Person 2 are honest and Person 3 is unkind, we have two honest persons without inconsistencies, which is the maximum possible number of honest persons.

Sample Input 2

3
2
2 1
3 0
2
3 1
1 0
2
1 1
2 0

Sample Output 2

0

Assuming that one or more of them are honest immediately leads to a contradiction.

Sample Input 3

2
1
2 0
1
1 0

Sample Output 3

1


;; D - Xor Sum 4

(defparameter *modulus* (+ (expt 10 9) 7))
(defparameter *max-bits* 60)

(defun add-bits-to-vector (n vec)
  "配列vecに整数nの2進各桁を加える"
  (loop for m = n then (ash m -1) until (zerop m)
        for i from 0
        do (incf (aref vec i) (logand m 1))))

(defun solve (N)
  (let ((vec (make-array *max-bits* :initial-element 0)))
    ; 各数を2進数に変換したときの各桁の1の個数を求める
    (loop repeat N do (add-bits-to-vector (read) vec))
    ; 各桁を集約
    (reduce #'(lambda (l h) (mod (+ l (ash h 1)) *modulus*))
      ; 2進各桁のXORの総和 (= 1の個数 * 0の個数)
      (map 'vector #'(lambda (m) (* m (- N m))) vec)
      :from-end t)))

(defun main ()
  (print (solve (read)))
  (fresh-line))

(main)

Score : 400 points

Problem Statement

We have N integers. The i-th integer is A_i.

Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

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

0 \leq A_i < 2^{60}

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 value \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

6

We have (1\mbox{ XOR } 2)+(1\mbox{ XOR } 3)+(2\mbox{ XOR } 3)=3+2+1=6.

Sample Input 2

10
3 1 4 1 5 9 2 6 5 3

Sample Output 2

237

Sample Input 3

10
3 14 159 2653 58979 323846 2643383 27950288 419716939 9375105820

Sample Output 3

103715602

Print the sum modulo (10^9+7).


;; D - Xor Sum 4

(defparameter *modulus* (+ (expt 10 9) 7))
(defparameter *max-bits* 60)

(defun main ()
  (let* ((N (read))
         (A (loop repeat N collect (read))))
    (print (solve N A))
    (fresh-line)))

(defun solve (N A)
  ; 各桁を集約
  (reduce #'(lambda (l h) (mod (+ l (ash h 1)) *modulus*))
    ; 2進各桁のXORの総和 (= 1の個数 * 0の個数)
    (map 'vector #'(lambda (m) (* m (- N m)))
      ; 各数を2進各桁のベクトルに変換し和 (2進各桁の1の個数) を求める
      (loop with vec = (to-bit-vector (car A))
            for elem in (cdr A)
            do (map-into vec #'+ vec (to-bit-vector elem))
            finally (return vec)))
    :from-end t))

(defun to-bit-vector (n)
  "整数nを2進各桁の配列 (最下位が前) に変換"
  (loop with vec = (make-array *max-bits*)
        for i from 0 below *max-bits*
        for m = n then (ash m -1) do (setf (aref vec i) (mod m 2))
        finally (return vec)))

(compile 'to-bit-vector)
(compile 'solve)

(main)


(let* ((n (read))
       (a (loop repeat n
             collect (read)))
       (count 0) b)
  (princ (mod
          (loop for c from 0 to 59
             with q
             do (setq q (mod (ash 1 c) 1000000007))
             do (setq count 0)
             do (loop for x in a
                   if (eq (mod (ash x (- c)) 2) 1)
                   do (setq count (1+ count))
                   finally (setq b (* count (- n count) q)))
             sum (mod b 1000000007))
          1000000007)))


;; E - Balanced Path

(defun main ()
  (let* ((H (read))
         (W (read))
         (A (loop repeat H collect (loop repeat W collect (read))))
         (B (loop repeat H collect (loop repeat W collect (read)))))
    (print (solve H W A B))
    (fresh-line)))

(defmacro table-add (table i j elem)
  `(setf (aref ,table ,i ,j ,elem) 1))
(defmacro table-contains (table i j elem)
  `(plusp (aref ,table ,i ,j ,elem)))

(defun solve (H W A B)
  (let* ((maxdiff (* 80 (+ W H)))
         (D (make-array (list H W) :initial-contents
              (mapcar #'(lambda (a b) (mapcar #'- a b)) A B)))
         (table (make-array (list H W maxdiff) :element-type 'bit
                  :initial-element 0)))

    ; table[0, 0]を初期化
    (table-add table 0 0 (abs (aref D 0 0)))

    ; table[i, j]を計算
    (loop for i below H do
      (loop for j below W
            for diff = (aref D i j) do
        (loop for prev below maxdiff
          when (or (and (plusp j) (table-contains table i (1- j) prev))
                   (and (plusp i) (table-contains table (1- i) j prev)))
          do (table-add table i j (abs (+ prev diff)))
             (table-add table i j (abs (- prev diff))))))

    ; table[H-1, W-1]の最小値
    (loop for d from 0
      when (table-contains table (1- H) (1- W) d)
      return d)))

(main)

Score : 500 points

Problem Statement

We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.

The square (i, j) has two numbers A_{ij} and B_{ij} written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

Sample Input 2

2 3
1 10 80
80 10 1
1 2 3
4 5 6

Sample Output 2

2


;; -*- 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
(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))
         (x (read))
         (d (read))
         (table (make-hash-table :test #'eq))
         (res 0))
    (declare (uint31 n)
             (int32 x d)
             (uint62 res))
    (when (zerop d)
      (if (zerop x)
          (println 0)
          (println (+ n 1)))
      (return-from main))
    (when (< d 0)
      (setq d (- d)
            x (- x)))
    (loop for p from 0 to n
          for rem = (mod (* p x) d)
          for init-idx of-type uint31 = (ash (* p (- p 1)) -1)
          for end-idx of-type uint31 = (+ 1
                                          (- (ash (* n (- n 1)) -1)
                                             (ash (* (- n p) (- n p 1)) -1)))
          do (dbg init-idx end-idx)
             (push (cons (+ (* p x) (* d init-idx)) 1)
                   (gethash rem table))
             (push (cons (+ (* p x) (* d end-idx)) -1)
                   (gethash rem table)))
    (labels ((recur (list prev depth)
               (declare (fixnum prev depth))
               (when list
                 (destructuring-bind (pos . dir) (car list)
                   (declare (fixnum pos dir))
                   (if (= dir 1)
                       (if (= depth 0)
                           (recur (cdr list) pos 1)
                           (recur (cdr list) prev (+ depth 1)))
                       (if (= depth 1)
                           (progn
                             (incf res (- pos prev))
                             (recur (cdr list) 0 0))
                           (recur (cdr list) prev (- depth 1))))))))
      (loop for key being each hash-key of table
            do (setf (gethash key table)
                     (sort (the list (gethash key table))
                           (lambda (x y)
                             (declare ((cons fixnum fixnum) x y))
                             (or (< (car x) (car y))
                                 (and (= (car x) (car y))
                                      (< (cdr x) (cdr y))))))))
      (loop for nodes being each hash-value of table
            do (recur nodes 0 0))
      (println (/ res d))
      table)))

#-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:/msys64/usr/bin/cat.exe" '("/dev/clipboard") :output out)))

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3 4 2
"
    "8
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2 3 -3
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "100 14 20
"
    "49805
")))

Score : 600 points

Problem Statement

We have an integer sequence A of length N, where A_1 = X, A_{i+1} = A_i + D (1 \leq i < N ) holds.

Takahashi will take some (possibly all or none) of the elements in this sequence, and Aoki will take all of the others.

Let S and T be the sum of the numbers taken by Takahashi and Aoki, respectively. How many possible values of S - T are there?

Constraints

-10^8 \leq X, D \leq 10^8

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X D

Output

Print the number of possible values of S - T.

Sample Input 1

3 4 2

Sample Output 1

8

A is (4, 6, 8).

There are eight ways for (Takahashi, Aoki) to take the elements: ((), (4, 6, 8)), ((4), (6, 8)), ((6), (4, 8)), ((8), (4, 6))), ((4, 6), (8))), ((4, 8), (6))), ((6, 8), (4))), and ((4, 6, 8), ()).

The values of S - T in these ways are -18, -10, -6, -2, 2, 6, 10, and 18, respectively, so there are eight possible values of S - T.

Sample Input 2

2 3 -3

Sample Output 2

2

A is (3, 0). There are two possible values of S - T: -3 and 3.

Sample Input 3

100 14 20

Sample Output 3

49805