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

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (m (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         ;; -1: unspecified, 0: red, 1: black
         (colors (make-array n :element-type 'int8 :initial-element -1))
         (dp (make-array n :element-type 'fixnum :initial-element 0)))
    (dotimes (i m)
      (let ((u (- (read-fixnum) 1))
            (v (- (read-fixnum) 1))
            (s (read-fixnum)))
        (push (cons u s) (aref graph v))
        (push (cons v s) (aref graph u))))
    (block proc
      (labels ((write-and-return (x)
                 (println x)
                 (return-from main))
               (answer ()
                 (let ((min0 (loop for v below n
                                   when (= (aref colors v) 0)
                                   minimize (aref dp v)))
                       (min1 (loop for v below n
                                   when (= (aref colors v) 1)
                                   minimize (aref dp v))))
                   (write-and-return (max 0 (+ min0 min1 -1)))))
               (dfs (v value color loop-count)
                 (dbg v value color loop-count)
                 (cond ((= (aref colors v) -1)
                        (setf (aref colors v) color
                              (aref dp v) value)
                        (loop for (neighbor . potential) in (aref graph v)
                              do (dfs neighbor
                                      (- potential value)
                                      (logxor color 1)
                                      loop-count)))
                       ((= (aref colors v) color)
                        (unless (= value (aref dp v))
                          (write-and-return 0)))
                       ;; odd cycle
                       ((= (aref dp v) value)
                        (dfs-odd v value)
                        (write-and-return
                         (if (every (lambda (x) (> x 0)) dp) 1 0)))
                       ((and (evenp (- value (aref dp v)))
                             (zerop loop-count))
                        (fill colors -1)
                        (fill dp 0)
                        (dfs v (ash (+ value (aref dp v)) -1) 0 (+ 1 loop-count))
                        (answer))
                       (t (write-and-return 0))))
               (dfs-odd (v value)
                 (error "Huh?")
                 (cond ((= (aref colors v) -1)
                        (setf (aref colors v) 1
                              (aref dp v) value)
                        (loop for (neighbor . potential) in (aref graph v)
                              do (dfs-odd neighbor (- potential value))))
                       ((/= (aref dp v) value)
                        (write-and-return 0)))))
        (dfs 0 0 0 0)
        (answer)))))

#-swank (main)

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

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

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

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

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

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

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

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

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


(defun hoge ()
  (let ((n (read)))
    (if (oddp n)
        (format t "~D~%" (* n 2))
        (format t "~D~%" n))))

(hoge)

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

Score : 100 points

Problem Statement

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

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

3

Sample Output 1

6

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

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998

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 func (x)
  (if (oddp x)
	(* x 2)
	x))

(princ (func (read)))


(defun ans (n)
  (if (evenp n) n (* n 2)))

(format t "~a~%" (ans (read)))


(let* ((n (read)))
(print (if (mod n 2) n (* n 2))))


(let ((n (read)))
  (declare (fixnum n)
           (optimize (safety 0) (speed 3) (debug 0)))
  (princ (if (zerop (rem n 2))
             n
             (* 2 n))))


(let ((N (read))) (if (oddp N) (princ (* 2 N)) (princ N)))


(defun solver ()
  (let ((n (read)))
    (if (zerop (mod n 2))
        (format t "~a~%" n)
        (format t "~a~%" (* n 2)))))

(solver)


(defparameter n (read))
(defparameter s (read-line))

(defun split-py (str)
  (let ((pos (position #\space str)))
    (cond ((null pos) (list str))
           (t (cons (subseq str 0 pos) (split-py (subseq str (1+ pos))))))))

; incf は1+してsetq
; 1+ は1+した値を返すだけ

(let ((L (sort (mapcar (lambda (x) (read-from-string x)) (split-py s)) #'<)))
  (princ (- (car (last L)) (first L))))

Score : 200 points

Problem Statement

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

Constraints

2 \leq N \leq 100

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

4
1 4 6 3

Sample Output 1

5

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

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


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

(defun chuou (b-lst)
  (let* ((len (length b-lst))
         (chuou-n (floor len 2))
         (new-lst (sort b-lst #'<)))
    (if (oddp len)
        (nth chuou-n new-lst)
        (let ((c1 (nth chuou-n new-lst))
              (c2 (nth (1- chuou-n) new-lst)))
          (floor (+ c1 c2) 2)))))

(defun hoge ()
  (let* ((lst (moge))
         (b-lst (loop :for a :in lst
                      :for i :from 1
                      :collect (- a i)))
         (b (chuou b-lst))
         (v (loop :for a :in lst
                  :for i :from 1
                  :sum (abs (- a (+ b i))))))
    (format t "~D~%" v)))

(hoge)

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

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

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

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

Find the minimum possible sadness of Snuke.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

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

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


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

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


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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (as (make-array n :element-type 'uint32))
         (cumuls (make-array (+ n 1) :element-type 'uint62 :initial-element 0))
         (res most-positive-fixnum))
    (declare (uint62 n res))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)
            (aref cumuls (+ i 1)) (+ (aref cumuls i) (aref as i))))
    (labels ((query (l r)
               (- (aref cumuls r) (aref cumuls l))))
      (declare (inline query))
      (loop for pivot from 2 to (- n 2)
            do (labels ((query-pq (i)
                          (abs (- (query 0 i) (query i pivot))))
                        (query-rs (i)
                          (abs (- (query pivot i) (query i n)))))
                 (declare (inline query-pq query-rs))
                 (let* ((qtile1 (sb-int:named-let bisect ((ng 0) (ok pivot))
                                  (declare (uint32 ng ok))
                                  (if (<= (- ok ng) 1)
                                      ok
                                      (let ((mid (ash (+ ok ng) -1)))
                                        (if (>= (query-pq (+ mid 1))
                                                (query-pq mid))
                                            (bisect ng mid)
                                            (bisect mid ok))))))
                        (qtile3 (sb-int:named-let bisect ((ng pivot) (ok n))
                                  (declare (uint32 ng ok))
                                  (if (<= (- ok ng) 1)
                                      ok
                                      (let ((mid (ash (+ ok ng) -1)))
                                        (if (>= (query-rs (+ mid 1))
                                                (query-rs mid))
                                            (bisect ng mid)
                                            (bisect mid ok))))))
                        (p (query 0 qtile1))
                        (q (query qtile1 pivot))
                        (r (query pivot qtile3))
                        (s (query qtile3 n)))
                   (dbg pivot qtile1 qtile3 p q r s)
                   (setq res (min res (- (max p q r s) (min p q r s))))))))
    (println res)))

#-swank (main)

Score : 600 points

Problem Statement

Snuke has an integer sequence A of length N.

He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E.
The positions of the cuts can be freely chosen.

Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively.
Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller.
Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Sample Input 1

5
3 2 4 1 2

Sample Output 1

2

If we divide A as B,C,D,E=(3),(2),(4),(1,2), then P=3,Q=2,R=4,S=1+2=3.
Here, the maximum and the minimum among P,Q,R,S are 4 and 2, with the absolute difference of 2.
We cannot make the absolute difference of the maximum and the minimum less than 2, so the answer is 2.

Sample Input 2

10
10 71 84 33 6 47 23 25 52 64

Sample Output 2

36

Sample Input 3

7
1 2 3 1000000000 4 5 6

Sample Output 3

999999994


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

;; BEGIN_INSERTED_CONTENTS
(declaim (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))
         (cumuls (make-array (+ n 1) :element-type 'uint62 :initial-element 0))
         (res most-positive-fixnum))
    (declare (uint62 n res))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)
            (aref cumuls (+ i 1)) (+ (aref cumuls i) (aref as i))))
    (labels ((query (l r)
               (- (aref cumuls r) (aref cumuls l))))
      (loop for pivot from 2 to (- n 2)
            do (labels ((query-pq (i)
                          (abs (- (query 0 i) (query i pivot))))
                        (query-rs (i)
                          (abs (- (query pivot i) (query i n)))))
                 (let* ((qtile1 (sb-int:named-let bisect ((ng 0) (ok pivot))
                                  (declare (uint32 ng ok))
                                  (if (<= (- ok ng) 1)
                                      ok
                                      (let ((mid (ash (+ ok ng) -1)))
                                        (if (>= (query-pq (+ mid 1))
                                                (query-pq mid))
                                            (bisect ng mid)
                                            (bisect mid ok))))))
                        (qtile3 (sb-int:named-let bisect ((ng pivot) (ok n))
                                  (declare (uint32 ng ok))
                                  (if (<= (- ok ng) 1)
                                      ok
                                      (let ((mid (ash (+ ok ng) -1)))
                                        (if (>= (query-rs (+ mid 1))
                                                (query-rs mid))
                                            (bisect ng mid)
                                            (bisect mid ok))))))
                        (p (query 0 qtile1))
                        (q (query qtile1 pivot))
                        (r (query pivot qtile3))
                        (s (query qtile3 n)))
                   (dbg pivot qtile1 qtile3 p q r s)
                   (setq res (min res (- (max p q r s) (min p q r s))))))))
    (println res)))

#-swank (main)


(defun get-max (data start end)
  (if (zerop start)
      (aref data (1- end))
      (- (aref data (1- end))
         (aref data (1- start)))))

(defun get-diff (data start-point second-point end-point)
  (abs (- (get-max data second-point end-point)
          (get-max data start-point second-point))))

(defun equal-cut ()
  (declare (optimize (speed 3) (safety 0) (debug 0) (space 0)))
  (let* ((n (read))
         (data (make-array n :initial-contents (loop repeat n
                                                     sum (read) into summed-a
                                                     collect summed-a))))
    (loop for second-separator from 2 below (1- n)
          with first-separator = 1
          with third-separator = 3
          with minimized-diff = #.(* (* 2 (expt 10 5)) (expt 10 9))
          when (>= second-separator third-separator)
            do (setq third-separator (1+ second-separator))
          do (loop (if (and (< first-separator (1- second-separator))
                            (< (get-diff data 0 (1+ first-separator) second-separator)
                               (get-diff data 0 first-separator second-separator)))
                       (incf first-separator)
                       (return)))
             (loop (if (and (< third-separator (1- n))
                            (< (get-diff data second-separator (1+ third-separator) n)
                               (get-diff data second-separator third-separator n)))
                       (incf third-separator)
                       (return)))
             (let* ((max-list (list (get-max data 0 first-separator)
                                    (get-max data first-separator second-separator)
                                    (get-max data second-separator third-separator)
                                    (get-max data third-separator n)))
                    (diff (- (apply #'max max-list) (apply #'min max-list))))
               (if (< diff minimized-diff)
                   (setq minimized-diff diff)))
          finally (princ minimized-diff))))

(equal-cut)


(let ((data))
  (defun init-data (n)
    (setq data (make-array n :initial-contents (loop repeat n for an = (read) sum an into sum-a collect sum-a))))

  (defun get-sum (start end)
    (if (zerop start)
        (aref data (1- end))
        (- (aref data (1- end)) (aref data (1- start)))))

  (defun get-split-sum (start end)
    (labels ((get-split-sum (current-split-point diff-min split-point)
               (if (< current-split-point end)
                   (let ((diff (abs (- (get-sum current-split-point end)
                                       (get-sum start current-split-point)))))
                     (if (< diff diff-min)
                         (get-split-sum (1+ current-split-point) diff current-split-point)
                         (get-split-sum (1+ current-split-point) diff-min split-point)))
                   (values (get-sum start split-point)
                           (get-sum split-point end)))))
      (get-split-sum (1+ start) #.(expt 10 9) (1+ start)))))

(defun equal-cut ()
  (declare (optimize (speed 3) (debug 0) (safety 0) (space 0)))
  (let ((n (read))
        (diff-min #.(expt 10 9)))
    (init-data n)
    (loop for second-split-point from 2 below (- n 2) do
      (multiple-value-call #'(lambda (b-sum c-sum d-sum e-sum)
                               (let* ((sum-list (list b-sum c-sum d-sum e-sum))
                                      (diff (- (apply #'max sum-list)
                                               (apply #'min sum-list))))
                                 (when (< diff diff-min)
                                   (setq diff-min diff))))
        (get-split-sum 0 second-split-point)
        (get-split-sum second-split-point n)))
    (princ diff-min)))

(equal-cut)


(let ((data))
  (defun init-data (n)
    (setq data (make-array n :initial-contents (loop repeat n for an = (read) sum an into sum-a collect sum-a))))

  (defun get-sum (start end)
    (if (zerop start)
        (aref data (1- end))
        (- (aref data (1- end)) (aref data (1- start))))))

(defun equal-cut ()
  (let ((n (read))
        (min-diff #.(expt 10 9)))
    (init-data n)
    (loop for i from 1 below (- n 2) do
      (loop for j from (1+ i) below (- n 1) do
        (loop for k from (1+ j) below n do
          (let* ((sum-list (list (get-sum 0 i) (get-sum i j) (get-sum j k) (get-sum k n)))
                 (diff (- (apply #'max sum-list) (apply #'min sum-list))))
            (when (< diff min-diff)
              (setq min-diff diff))))))
    (princ min-diff)))

(equal-cut)


(princ (loop for predicate in (map 'list
                                   (lambda (predicate-char)
                                     (intern (string predicate-char)))
                                   (read-line))
             sum (eval `(,predicate 0 1))))

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

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

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

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

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

+-++

Sample Output 1

2

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

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

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

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

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

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

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


(labels ((solver (predicates num)
           (if predicates
               (solver (cdr predicates) (if (char= #\+ (car predicates))
                                            (1+ num)
                                            (1- num)))
               num)))
  (princ (solver (coerce (read-line) 'list) 0)))


(defparameter n (read-line))
(defparameter digit (read-from-string n))
(defparameter total
  (reduce #'(lambda (m x) (+ x m))
    (mapcar (lambda (x) (parse-integer (string x))) (coerce n 'list))))

(if (= (mod digit total) 0) (princ "Yes") (princ "No"))

Score : 200 points

Problem Statement

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

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

Constraints

1 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

12

Sample Output 1

Yes

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

Sample Input 2

101

Sample Output 2

No

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

Sample Input 3

999999999

Sample Output 3

Yes


(let ((n (read)))
  (princ
    (if (= 0
           (mod n
             (apply #'+
                    (mapcar (lambda (x) (- (char-int x) 48))
                            (coerce (write-to-string n) 'list)))))
        "Yes"
        "No")))


(princ (ceiling (1- (read)) (1- (read))))

Score : 300 points

Problem Statement

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

On this sequence, Snuke can perform the following operation:

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

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

Constraints

2 \leq K \leq N \leq 100000

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

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

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

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

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


(let* ((n (read))
       (k (read))
       (a (loop repeat n collect (read))))
  (princ (1+ (ceiling (/ (- n k) (1- k))))))


(let* ((n (read))
       (k (read))
       (a (loop repeat n collect (read)))
       (pos-1 (position 1 a)))
  (princ
    (+ (ceiling (/ pos-1 (1- k)))
       (ceiling (/ (- n (1+ pos-1)) (1- k))))))


;; -*- 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 integer-length*))
(defun integer-length* (x &optional (radix 10))
  "Returns the length of the integer X when displayed in RADIX. (Returns 0 when
X = 0. Ignores the negative sign.)"
  (declare (integer x)
           ((integer 2 #.most-positive-fixnum) radix))
  (loop for length of-type (integer 0 #.most-positive-fixnum) from 0
        for y = (abs x) then (floor y radix)
        until (zerop y)
        finally (return length)))

(declaim (inline digit-sum))
(defun digit-sum (x &optional (radix 10))
  "Returns the sum of the each digit of X w.r.t. RADIX. (Returns 0 when X =
0. Ignores the negative sign.)"
  (declare (integer x)
           ((integer 2 #.most-positive-fixnum) radix))
  (let ((sum 0)
        (x (abs x)))
    (declare (unsigned-byte x)
             ((integer 0 #.most-positive-fixnum) sum))
    (loop
      (when (zerop x)
        (return sum))
      (multiple-value-bind (quot rem) (floor x radix)
        (incf sum rem)
        (setq x quot)))))

(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 frob (function x mask-width)
  (declare (uint62 x)
           (uint8 mask-width)
           (function function))
  (let* ((tens (expt 10 mask-width))
         (nines (- tens 1))
         (upper-base (floor x tens))
         (upper-limit (* 100 (ceiling (+ 1 upper-base) 100))))
    (declare (uint62 tens nines upper-base upper-limit))
    (loop for upper from upper-base below upper-limit
          do (funcall function (+ (* upper tens) nines)))))

(defun calc-next-snuke (n)
  (let ((width (integer-length* n))
        (min-val most-positive-fixnum)
        (res 0))
    (declare (rational min-val)
             (uint62 res))
    (loop for mask-width from 0 below width
          do (frob (lambda (x)
                     (declare (uint62 x))
                     (let ((val (/ x (digit-sum x))))
                       ;; (dbg x val)
                       (when (or (< val min-val)
                                 (and (= val min-val)
                                      (< x res)))
                         (setq res x
                               min-val val))))
                   n
                   mask-width))
    (assert (not (zerop res)))
    res))

(defun main ()
  (let* ((k (read))
         (val 1))
    (dotimes (_ k)
      (println val)
      (setq val (calc-next-snuke (+ val 1))))))

#-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 "10
"
    "1
2
3
4
5
6
7
8
9
19
")))

Score : 500 points

Problem Statement

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

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

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

Constraints

1 \leq K

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

Input

Input is given from Standard Input in the following format:

K

Output

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

Sample Input 1

10

Sample Output 1

1
2
3
4
5
6
7
8
9
19


Score: 100 points

Problem Statement

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

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

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

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

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

Constraints

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

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

5 4

Sample Output 1

Yay!

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

Sample Input 2

8 8

Sample Output 2

Yay!

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

Sample Input 3

11 4

Sample Output 3

:(

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


(defun app ()
    (if (< (read) 1000)
        (format t "ABC~%")
        (format t "ABD~%")
    )
)
(app)

Score : 100 points

Problem Statement

Decades have passed since the beginning of AtCoder Beginner Contest.

The contests are labeled as ABC001, ABC002, ... from the first round, but after the 999-th round ABC999, a problem occurred: how the future rounds should be labeled?

In the end, the labels for the rounds from the 1000-th to the 1998-th are decided: ABD001, ABD002, ..., ABD999.

You are given an integer N between 1 and 1998 (inclusive). Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Constraints

1 \leq N \leq 1998

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Sample Input 1

999

Sample Output 1

ABC

The 999-th round of AtCoder Beginner Contest is labeled as ABC999.

Sample Input 2

1000

Sample Output 2

ABD

The 1000-th round of AtCoder Beginner Contest is labeled as ABD001.

Sample Input 3

1481

Sample Output 3

ABD

The 1481-th round of AtCoder Beginner Contest is labeled as ABD482.


(let ((n (read)))
  (if (< n 1000)
      (format t "ABC~%")
      (format t "ABD~%")))


(princ (if (< (read) 1000) "ABC" "ABD"))


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

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

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

(defconstant +mod+ 1000000007)

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

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

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

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

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

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

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

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

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

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

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

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

(defparameter *inf* 100000000)

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

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

#-swank (main)

Score : 300 points

Problem Statement

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

1 yen (the currency of Japan)

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

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

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

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

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

127

Sample Output 1

4

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

Sample Input 2

3

Sample Output 2

3

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

Sample Input 3

44852

Sample Output 3

16


(defun app ()
    (let* ((n (read))
        (ans n))
    (dotimes (i n)
        (let ((a 0)
            (b i))
            (loop while (> b 0) do
                (progn
                (setq a (+ a (rem b 6)))
                (setq b (floor (/ b 6))))
            )
            (setq b (- n i))
            (loop while (> b 0) do
                (progn
                (setq a (+ a (rem b 9)))
                (setq b (floor (/ b 9))))
            )
            (if (> ans a)
            (setq ans a))
        )
    )
    (format t "~D~%" ans))
)
(app)


(let ((n (read))
      (a '())
      (ans 0))
  (loop for i from 1 while (<= (expt 6 i) n) do
        (setf a (append a (list (expt 6 i) (expt 9 i)))))
  (setf a (sort (copy-list a) #'>))
  (loop for i in a do
        (if (<= i n) (progn (incf ans (floor (/ n i)))
                           (setf n (rem n i)))))
  (format t "~A~%" (+ ans n)))


(let ((n (read))
      (a '())
      (ans 0))
  (loop for i from 1 while (< (expt 6 i) n) do
        (setf a (append a (list (expt 6 i) (expt 9 i)))))
  (setf a (sort (copy-list a) #'>))
  (loop for i in a do
        (if (<= i n) (progn (incf ans (floor (/ n i)))
                           (setf n (rem n i)))))
  (format t "~A~%" (+ ans n)))


 (let ((n (read)))
  (labels ((maxpower (n x)
             (labels ((iter (n x c)
                        (if (<= (expt x c) n)
                            (iter n x (1+ c))
                            (expt x (1- c)))))
               (iter n x 1)))
           (f (n n6 n9)
             (let ((nlarge (max n6 n9)))
               (if (= nlarge 1)
                   n
                   (1+ (let ((new-n (- n nlarge)))
                     (f new-n (maxpower new-n 6) (maxpower new-n 9))))))))
    (format t "~A~%" (f n (maxpower n 6) (maxpower n 9)))))


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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (c (read))
         (ds (make-array (list c c) :element-type 'uint16))
         (table0 (make-array c :element-type 'uint32))
         (table1 (make-array c :element-type 'uint32))
         (table2 (make-array c :element-type 'uint32)))
    (declare (uint16 n c))
    (dotimes (i c)
      (dotimes (j c)
        (setf (aref ds i j) (read-fixnum))))
    (dotimes (i n)
      (dotimes (j n)
        (let ((col (- (read-fixnum) 1)))
          (ecase (mod (+ i j) 3)
            (0 (incf (aref table0 col)))
            (1 (incf (aref table1 col)))
            (2 (incf (aref table2 col)))))))
    (let ((res #xffffffff))
      (declare (uint32 res))
      (dotimes (col0 c)
        (dotimes (col1 c)
          (dotimes (col2 c)
            (unless (or (= col0 col1) (= col1 col2) (= col2 col0))
              (setf res
                    (min res
                         (+ (loop for scol below c
                                  sum (* (aref ds scol col0) (aref table0 scol))
                                  of-type uint32)
                            (loop for scol below c
                                  sum (* (aref ds scol col1) (aref table1 scol))
                                  of-type uint32)
                            (loop for scol below c
                                  sum (* (aref ds scol col2) (aref table2 scol))
                                  of-type uint32))))))))
      (println res))))

#-swank(main)

Score : 400 points

Problem Statement

There is a grid with N rows and N columns of squares. Let (i,j) be the square at the i-th row from the top and the j-th column from the left.

These squares have to be painted in one of the C colors from Color 1 to Color C. Initially, (i,j) is painted in Color c_{i,j}.

We say the grid is a good grid when the following condition is met for all i,j,x,y satisfying 1 \leq i,j,x,y \leq N:

If (i+j) \% 3=(x+y) \% 3, the color of (i,j) and the color of (x,y) are the same.

If (i+j) \% 3 \neq (x+y) \% 3, the color of (i,j) and the color of (x,y) are different.

Here, X \% Y represents X modulo Y.

We will repaint zero or more squares so that the grid will be a good grid.

For a square, the wrongness when the color of the square is X before repainting and Y after repainting, is D_{X,Y}.

Find the minimum possible sum of the wrongness of all the squares.

Constraints

1 \leq N \leq 500

3 \leq C \leq 30

1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)

1 \leq c_{i,j} \leq C

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N C
D_{1,1} ... D_{1,C}
:
D_{C,1} ... D_{C,C}
c_{1,1} ... c_{1,N}
:
c_{N,1} ... c_{N,N}

Output

If the minimum possible sum of the wrongness of all the squares is x, print x.

Sample Input 1

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

Sample Output 1

3

Repaint (1,1) to Color 2. The wrongness of (1,1) becomes D_{1,2}=1.

Repaint (1,2) to Color 3. The wrongness of (1,2) becomes D_{2,3}=1.

Repaint (2,2) to Color 1. The wrongness of (2,2) becomes D_{3,1}=1.

In this case, the sum of the wrongness of all the squares is 3.

Note that D_{i,j} \neq D_{j,i} is possible.

Sample Input 2

4 3
0 12 71
81 0 53
14 92 0
1 1 2 1
2 1 1 2
2 2 1 3
1 1 2 2

Sample Output 2

428


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

;; BEGIN_INSERTED_CONTENTS
(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))
         (c (read))
         (ds (make-array (list c c) :element-type 'uint16))
         (table0 (make-array c :element-type 'uint32))
         (table1 (make-array c :element-type 'uint32))
         (table2 (make-array c :element-type 'uint32)))
    (declare (uint16 n c))
    (dotimes (i c)
      (dotimes (j c)
        (setf (aref ds i j) (read-fixnum))))
    (dotimes (i n)
      (dotimes (j n)
        (let ((col (- (read-fixnum) 1)))
          (ecase (mod (+ i j) 3)
            (0 (incf (aref table0 col)))
            (1 (incf (aref table1 col)))
            (2 (incf (aref table2 col)))))))
    (let ((res #xffffffff))
      (declare (uint32 res))
      (dotimes (col0 c)
        (dotimes (col1 c)
          (dotimes (col2 c)
            (unless (or (= col0 col1) (= col1 col2) (= col2 col0))
              (setf res
                    (min res
                         (+ (loop for scol below c
                                  sum (* (aref ds scol col0) (aref table0 scol))
                                  of-type uint32)
                            (loop for scol below c
                                  sum (* (aref ds scol col1) (aref table1 scol))
                                  of-type uint32)
                            (loop for scol below c
                                  sum (* (aref ds scol col2) (aref table2 scol))
                                  of-type uint32))))))))
      (println res))))

#-swank(main)


;; -*- 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 integer-length*))
(defun integer-length* (x &optional (radix 10))
  "Returns the length of the integer X when displayed in RADIX. (Returns 0 when
X = 0. Ignores the negative sign.)"
  (declare (integer x)
           ((integer 2 #.most-positive-fixnum) radix))
  (loop for length of-type (integer 0 #.most-positive-fixnum) from 0
        for y = (abs x) then (floor y radix)
        until (zerop y)
        finally (return length)))

(declaim (inline digit-sum))
(defun digit-sum (x &optional (radix 10))
  "Returns the sum of the each digit of X w.r.t. RADIX. (Returns 0 when X =
0. Ignores the negative sign.)"
  (declare (integer x)
           ((integer 2 #.most-positive-fixnum) radix))
  (let ((sum 0)
        (x (abs x)))
    (declare (unsigned-byte x)
             ((integer 0 #.most-positive-fixnum) sum))
    (loop
      (when (zerop x)
        (return sum))
      (multiple-value-bind (quot rem) (floor x radix)
        (incf sum rem)
        (setq x quot)))))

(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)))
    (println
     (loop for a from 1 to (floor n 2)
           for b = (- n a)
           minimize (+ (digit-sum a) (digit-sum b))))))

#-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 "15
"
    "6
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "100000
"
    "10
")))

Score : 200 points

Problem Statement

Takahashi has two positive integers A and B.

It is known that A plus B equals N.
Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).

Constraints

2 ≤ N ≤ 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B".

Sample Input 1

15

Sample Output 1

6

When A=2 and B=13, the sums of their digits are 2 and 4, which minimizes the value in question.

Sample Input 2

100000

Sample Output 2

10


(defun func (a b)
  (max (+ a b) (- a b) (* a b)))

(princ (func (read) (read)))

Score : 100 points

Problem Statement

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

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

3 1

Sample Output 1

4

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

Sample Input 2

4 -2

Sample Output 2

6

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

Sample Input 3

0 0

Sample Output 3

0


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


(defun AddSubMul (a b)
  (let ((n (+ a b)) (m (- a b)) (l (* a b)))
    (max n m l)))

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

(format t "~A~%"
  (apply #'AddSubMul (mapcar #'parse-integer (split-string (read-line)))))


(let* ((n (read))
       (s (make-array n :initial-contents (concatenate 'list (read-line)))))
  (format t "~A~%" (loop for i from 0 below (1- n)
                         minimize (+ (count-if (lambda (c) (equal #\W c)) (subseq s 0 i))
                                     (count-if (lambda (c) (equal #\E c)) (subseq s (1+ i)))))))

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


(defun Attention (str-list)
  (let ((saisyou 999999))
    (dotimes (i (length str-list))
      (let ((count 0) (result-count 0))
        (dolist (j str-list)
          (cond
            ((and (< count i) (char= j #\W)
                  (incf result-count)))
            ((and (> count i) (char= j #\E)
                  (incf result-count))))
          (incf count))
        (setf saisyou (min result-count saisyou))))
    (eval saisyou)))

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

(read-line)
(format t "~A~%" (Attention (coerce (read-line) 'list)))


(let ((a (read))
      (b (read))
      (c (read))
      (k (read)))
  (format t "~A~%" (if (oddp k) (- b a) (- a b))))

Score : 300 points

Problem Statement

Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively.
After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get:

Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own integer with the result.

However, if the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Constraints

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

0 \leq K \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the integer Takahashi will get minus the integer Nakahashi will get, after repeating the following operation K times.
If the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Sample Input 1

1 2 3 1

Sample Output 1

1

After one operation, Takahashi, Nakahashi and Hikuhashi have 5, 4 and 3, respectively. We should print 5-4=1.

Sample Input 2

2 3 2 0

Sample Output 2

-1

Sample Input 3

1000000000 1000000000 1000000000 1000000000000000000

Sample Output 3

0


(defun mul (a b)
  (let* ((dim (list (array-dimension a 0)
                    (array-dimension b 1)))
         (result (make-array dim :initial-element 0)))
    (loop for i below (array-dimension a 0)
          do (loop for j below (array-dimension b 1)
                   do (let ((acc 0))
                        (loop for k below (array-dimension a 1)
                              do (incf acc (* (aref a i k) (aref b k j))))
                        (setf (aref result i j) acc))))
    result))

(defparameter *S* #2a((-1 -1  1)
                      ( 0  1  1)
                      ( 1  0  1)))

(defparameter *J* #(-1 -1 2))

;; (defparameter *J2* #2a((-1  0  0)
;;                        ( 0 -1  0)
;;                        ( 0  0  2)))

(defparameter *S^-1* #2a((-1/3 -1/3  2/3)
                         (-1/3  2/3 -1/3)
                         ( 1/3  1/3  1/3)))

(defun make-diag (x y z)
  (let ((result (make-array '(3 3) :initial-element 0)))
    (setf (aref result 0 0) x
          (aref result 1 1) y
          (aref result 2 2) z)
    result))

(defun solve (a b c k)
  (let* ((diag (make-diag (expt -1 k)
                          (expt -1 k)
                          (expt  0 k)))
         (x (make-array '(3 1) :initial-contents `((,a) (,b) (,c))))
         (m (mul *S* (mul diag (mul *S^-1* x))))
         (a (- (aref m 0 0) (aref m 1 0))))
    (if (> a 1e18)
        "Unfair"
        a)))

(let ((a (read))
      (b (read))
      (c (read))
      (k (read)))
  (princ (solve a b c k))
  (terpri))


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

;; BEGIN_INSERTED_CONTENTS
(defun forest-p (graph)
  "Returns the length of the longest path of a directed GRAPH when it is a
forest, otherwise NIL."
  (declare ((array list (*)) graph))
  (let* ((n (length graph))
         (visited (make-array n :element-type 'bit :initial-element 0))
         (dp (make-array n :element-type 'fixnum :initial-element -1))
         (res 0))
    (declare ((integer 0 #.most-positive-fixnum) res))
    (labels ((recur (vertex)
               (if (= -1 (aref dp vertex))
                   (if (= 1 (aref visited vertex))
                       (return-from forest-p nil)
                       (setf (aref visited vertex) 1
                             (aref dp vertex)
                             (loop for next in (aref graph vertex)
                                   maximize (+ 1 (recur next)))))
                   (aref dp vertex))))
      (dotimes (i n)
        (when (zerop (aref visited i))
          (setf res (max res (recur i)))))
      res)))

(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 #\-))
                                  (setq minus t)))))))
      (declare ((integer 0 #.most-positive-fixnum) result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte 57)
              (setq result (+ (- byte 48)
                              (* 10 (the (integer 0 #.(floor most-positive-fixnum 10))
                                         result))))
              (return (if minus (- result) result))))))))

(in-package :cl-user)

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

(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))
         (ps (make-array n :element-type 'uint31 :initial-element 0))
         (invs (make-array n :element-type 'uint31 :initial-element 0))
         (graph (make-array n :element-type 'list :initial-element nil)))
    (dotimes (i n)
      (let ((p (- (read-fixnum) 1)))
        (setf (aref invs p) i)))
    (dotimes (i (- n 1))
      (when (< (aref invs i) (aref invs (+ i 1)))
        (push (+ i 1) (aref graph i))))
    #>graph
    (println (- n (+ 1 (forest-p graph))))))

#-swank (main)

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

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

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

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

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

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

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

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

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

Score : 500 points

Problem Statement

You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N.
You would like to sort this sequence in ascending order by repeating the following operation:

Choose an element in the sequence and move it to the beginning or the end of the sequence.

Find the minimum number of operations required.
It can be proved that it is actually possible to sort the sequence using this operation.

Constraints

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

(P_1,P_2,...,P_N) is a permutation of (1,2,...,N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1
:
P_N

Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4

Sample Output 1

2

For example, the sequence can be sorted in ascending order as follows:

Move 2 to the beginning. The sequence is now (2,1,3,4).

Move 1 to the beginning. The sequence is now (1,2,3,4).

Sample Input 2

6
3
2
5
1
4
6

Sample Output 2

4

Sample Input 3

8
6
3
1
2
7
4
8
5

Sample Output 3

5


(princ (let* ((a (read)) (b (read)) (c (read)) (d (read)))
  (if (<= (abs (- a c)) d) "Yes"
	(if (<= (min (abs (- a b)) (abs (- b c))) d) "Yes" "No"))))

Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


(let* ((n (read)))
  (princ (loop :for a :from 2 :upto (floor (sqrt 10)) :maximize(expt a (floor (log n a))))))

Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


(defun f (n a b)
  (cond ((or (= a 1) (= n 1)) b)
    ((= (rem n a) 0) (f (/ n a) a (1+ b)))
    (t 0)))

(let ((n (read))
      (flg t))
     (loop for i from n downto 1 while flg do
           (loop for j from i downto 1 while flg do
                 (if (< 1 (f i j 0)) (progn (princ i)
                                            (setf flg nil)))))
     (if flg (princ 1)))


;; -*- 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
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:defknown popcnt ((unsigned-byte 64)) (integer 0 64)
      (sb-c:foldable sb-c:flushable sb-c:movable)
    :overwrite-fndb-silently t)

  (sb-c:defknown popcnt ((unsigned-byte 64)) (integer 0 64)
      (sb-c:foldable sb-c:flushable sb-c:movable)
    :overwrite-fndb-silently t)

  (sb-vm::define-vop (popcnt)
    (:policy :fast-safe)
    (:translate popcnt)
    (:args (x :scs (sb-vm::unsigned-reg) :target r))
    (:arg-types sb-vm::unsigned-num)
    (:results (r :scs (sb-vm::unsigned-reg)))
    (:result-types sb-vm::unsigned-num)
    (:generator 3
                (unless (sb-vm::location= r x)
                  (sb-vm::inst xor r r))
                (sb-vm::inst popcnt r x)))

  (sb-vm::define-vop (popcnt/fx)
    (:policy :fast-safe)
    (:translate popcnt)
    (:args (x :scs (sb-vm::unsigned-reg) :target r))
    (:arg-types sb-vm::positive-fixnum)
    (:results (r :scs (sb-vm::unsigned-reg)))
    (:result-types sb-vm::unsigned-num)
    (:generator 2
                (unless (sb-vm::location= r x)
                  (sb-vm::inst xor r r))
                (sb-vm::inst popcnt r x))))

(defun popcnt (x)
  (popcnt x))

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

;;;
;;; Succinct bit vector
;;;

;; REVIEW: Is it really better to use the typical three-layer succint bit vector
;; in competitive programming? It may be efficient to use a two-layer (not
;; succinct but compact) bit vector preserving the original vector and the
;; cumulative sum per 64-bit word.

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

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

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

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

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

;;;
;;; Wavelet matrix
;;;

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

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

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

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

(define-condition invalid-wavelet-index-error (type-error)
  ((wavelet :initarg :wavelet :reader invalid-wavelet-index-error-wavelet)
   (index :initarg :index :reader invalid-wavelet-index-error-index))
  (:report
   (lambda (condition stream)
     (let ((index (invalid-wavelet-index-error-index condition)))
       (if (consp index)
           (format stream "Invalid range [~W, ~W) for wavelet-matrix ~W."
                   (car index)
                   (cdr index)
                   (invalid-wavelet-index-error-wavelet condition))
           (format stream "Invalid index ~W for wavelet-matrix ~W."
                   index
                   (invalid-wavelet-index-error-wavelet condition)))))))

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +inf+ (- (expt 2 11) 1))

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

#-swank (main)

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

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

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

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

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

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

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

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

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

Score : 600 points

Problem Statement

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

Takahashi the human wants to achieve the following objective:

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

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

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

Swap two adjacent balls.

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

Constraints

1 ≤ N ≤ 2000

1 ≤ a_i ≤ N

c_i = W or c_i = B.

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

4

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

Swap the black 3 and white 1.

Swap the white 1 and white 2.

Swap the black 3 and white 3.

Swap the black 3 and black 2.

Sample Input 2

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

Sample Output 2

18

Sample Input 3

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

Sample Output 3

41