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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(defun solve (n k)
  (* k (expt (1- k) (1- n))))

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

#-swank (main)

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

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

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


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

Submitted source-code file size, in bytes.

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

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


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

Score : 200 points

Problem Statement

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

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

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

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

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

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

Constraints

1≦N,A,B≦100000

A+B≦N

S is N characters long.

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

Input

Inputs are provided from Standard Input in the following form.

N A B
S

Output

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

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

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

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

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

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

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No


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

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

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

#-swank (main)

Score : 500 points

Problem Statement

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

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

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

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

Constraints

1 ≦ W,H ≦ 10^5

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

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

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

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

Input

Inputs are provided from Standard Input in the following form.

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

Output

Output an integer representing the minimum total cost.

Sample Input 1

2 2
3
5
2
7

Sample Output 1

29

It is enough to pave the following eight roads.

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

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

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

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

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

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

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

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

Sample Input 2

4 3
2
4
8
1
2
9
3

Sample Output 2

60


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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((x (read-line)))
    (println
     (sb-int:named-let recur ((pos 0) (unclosed-s 0) (res (length x)))
       (declare (uint31 pos unclosed-s res))
       (cond ((= pos (length x))
              res)
             ((char= #\S (aref x pos))
              (recur (+ pos 1) (+ unclosed-s 1) res))
             ((zerop unclosed-s)
              (recur (+ pos 1) unclosed-s res))
             (t
              (recur (+ pos 1) (- unclosed-s 1) (- res 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 "")))

#+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 "TSTTSS
"
    "4
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "SSTTST
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "TSSTTTSS
"
    "4
")))

Score : 300 points

Problem Statement

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

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

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

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

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

Partial Scores

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

Input

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

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

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

Sample Input 2

SSTTST

Sample Output 2

0

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

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


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

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

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

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

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

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

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

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

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

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

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

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

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

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

(defun make-cons (a b)
  (if (> a b) (cons b a)
      (cons a b)))

(defun main (lst)
  (- (length lst)
     (length
      (remove-duplicates
       (loop for i from 1
             for j in lst
             collect (make-cons i j))
       :test #'equal))))

(princ (main (read-times (read))))

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

Input

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

N
a_1 a_2 ... a_N

Output

Print the number of the friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


(defun main ()
  (let ((a (read))
        (b (read))
        (h (read)))
    (format t "~D~%" (/ (* (+ a b) h) 2))))

(main)

Score : 100 points

Problem Statement

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

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

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

a
b
h

Output

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

Sample Input 1

3
4
2

Sample Output 1

7

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

Sample Input 2

4
4
4

Sample Output 2

16

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


(defun bit-full-serarch (n)
  (let ((result nil))
    (do ((bit 0 (1+ bit)))
        ((> bit (ash 1 n)))
      (let ((tmp nil))
        (do ((i 0 (1+ i)))
            ((> i n))
          (when (/= 0 (logand  bit (ash 1 i)))
            (push i tmp)))
        (when tmp
          (push tmp result))
        ))
    result))

(defmacro char-list-to-string-to-number (l)
  `(parse-integer (coerce ,l 'string)))

(defun calc (target pos-list &optional (count 0) tmp result)
  (cond ((null target)
         (when tmp
           (let ((tmp-l (char-list-to-string-to-number (reverse tmp))))
             (if (null (listp tmp-l))
                 (push tmp-l result)
                 (push (reduce #'+ tmp-l) result))))
         (reverse result))
        ((and pos-list (= count (car pos-list)))
         (let ((tmp-l (char-list-to-string-to-number (reverse tmp))))
           (if (null (listp tmp-l))
               (push tmp-l result)
               (push (reduce #'+ tmp-l) result))
           (setq tmp nil))
         (push (car target) tmp)
         (calc (cdr target) (cdr pos-list) (- count 1) tmp result))
        (t
         (push (car target) tmp)
         (calc (cdr target) pos-list (- count 1) tmp result))))

(defun main ()
  (let* ((target (coerce (read-line) 'list))
         (pos-list (bit-full-serarch (- (length target) 1)))
         (result 0)
         (size (- (length target) 1)))
    ;; (print pos-list)
    (dolist (x pos-list)
      (if (= size (car x))
          (let ((tmp (parse-integer (coerce target 'string))))
            (setq result (+ result tmp)))
          (let ((tmp (calc target x (- (length target) 1))))
            ;; (format t "~%~A: ~A~%~%" x tmp)
            (setq result (+ result (reduce #'+ tmp)))
            )))
    (princ result)))

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq |S| \leq 10

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

Input

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

S

Output

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

Sample Input 1

125

Sample Output 1

176

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

125

1+25=26

12+5=17

1+2+5=8

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

Sample Input 2

9999999999

Sample Output 2

12656242944


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

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

(defmacro dx (form)
  (let ((tmp (gensym)))
    `(let ((,tmp ,form))
       (declare (dynamic-extent ,tmp))
       ,tmp)))

(defun main ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (n (read))
         (table (make-hash-table :test #'equal :size n))
         (res (make-array 10 :element-type 'uint32 :initial-element 0)))
    (declare (uint31 h w n))
    (dotimes (i n)
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (declare (uint32 a b))
        (setf (gethash (cons a b) table) t)))
    (labels ((frob (y x)
               (declare (int32 y x))
               (if (or (< y 0) (< x 0))
                   0
                   (let ((res 0)
                         (pair (cons 0 0)))
                     (declare (uint32 res)
                              ((cons fixnum fixnum) pair)
                              (sb-impl::truly-dynamic-extent pair))
                     (setf (car pair) y (cdr pair) x)
                     (when (gethash pair table) (incf res))
                     (setf (car pair) (+ y 1) (cdr pair) x)
                     (when (gethash pair table) (incf res))
                     (setf (car pair) (+ y 2) (cdr pair) x)
                     (when (gethash pair table) (incf res))
                     (setf (car pair) y (cdr pair) (+ x 1))
                     (when (gethash pair table) (incf res))
                     (setf (car pair) (+ y 1) (cdr pair) (+ x 1))
                     (when (gethash pair table) (incf res))
                     (setf (car pair) (+ y 2) (cdr pair) (+ x 1))
                     (when (gethash pair table) (incf res))
                     (setf (car pair) y (cdr pair) (+ x 2))
                     (when (gethash pair table) (incf res))
                     (setf (car pair) (+ y 1) (cdr pair) (+ x 2))
                     (when (gethash pair table) (incf res))
                     (setf (car pair) (+ y 2) (cdr pair) (+ x 2))
                     (when (gethash pair table) (incf res))
                     res))))
      (loop for (y . x) of-type (uint32 . uint32) being each hash-key of table
            do (when (< (+ y 2) h)
                 (when (< (+ x 2) w)
                   (incf (aref res (frob y x))))
                 (when (< (+ x 1) w)
                   (incf (aref res (frob y (- x 1)))))
                 (incf (aref res (frob y (- x 2)))))
               (when (< (+ y 1) h)
                 (when (< (+ x 2) w)
                   (incf (aref res (frob (- y 1) x))))
                 (when (< (+ x 1) w)
                   (incf (aref res (frob (- y 1) (- x 1)))))
                 (incf (aref res (frob (- y 1) (- x 2)))))
               (when (< (+ x 2) w)
                 (incf (aref res (frob (- y 2) x))))
               (when (< (+ x 1) w)
                 (incf (aref res (frob (- y 2) (- x 1)))))
               (incf (aref res (frob (- y 2) (- x 2)))))
      (loop for i from 1 to 9
            do (setf (aref res i) (/ (aref res i) i)))
      (println (- (* (- h 2) (- w 2))
                  (reduce #'+ res :start 1)))
      (loop for i from 1 to 9
            do (println (aref res i))))))

#-swank (main)

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. At first, all cells were painted white.

Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.

Compute the following:

For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells?

Constraints

3 \leq H \leq 10^9

3 \leq W \leq 10^9

0 \leq N \leq min(10^5,H×W)

1 \leq a_i \leq H (1 \leq i \leq N)

1 \leq b_i \leq W (1 \leq i \leq N)

(a_i, b_i) \neq (a_j, b_j) (i \neq j)

Input

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

H W N
a_1 b_1
:
a_N b_N

Output

Print 10 lines.
The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells.

Sample Input 1

4 5 8
1 1
1 4
1 5
2 3
3 1
3 2
3 4
4 4

Sample Output 1

0
0
0
2
4
0
0
0
0
0

There are six subrectangles of size 3×3. Two of them contain three black cells each, and the remaining four contain four black cells each.

Sample Input 2

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

Sample Output 2

4
26
22
10
2
0
0
0
0
0

Sample Input 3

1000000000 1000000000 0

Sample Output 3

999999996000000004
0
0
0
0
0
0
0
0
0


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

(defmacro dx (form)
  (let ((tmp (gensym)))
    `(let ((,tmp ,form))
       (declare (dynamic-extent ,tmp))
       ,tmp)))

(defun main ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (n (read))
         (table (make-hash-table :test #'equal :size n))
         (res (make-array 10 :element-type 'uint32 :initial-element 0)))
    (declare (uint31 h w n))
    (dotimes (i n)
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (declare (uint32 a b))
        (setf (gethash (cons a b) table) t)))
    (labels ((frob (y x)
               (declare (int32 y x))
               (if (or (< y 0) (< x 0))
                   0
                   (let ((res 0))
                     (declare (uint32 res))
                     (when (gethash (dx (cons y x)) table)
                       (incf res))
                     (when (gethash (dx (cons (+ y 1) x)) table)
                       (incf res))
                     (when (gethash (dx (cons (+ y 2) x)) table)
                       (incf res))
                     (when (gethash (dx (cons y (+ x 1))) table)
                       (incf res))
                     (when (gethash (dx (cons (+ y 1) (+ x 1))) table)
                       (incf res))
                     (when (gethash (dx (cons (+ y 2) (+ x 1))) table)
                       (incf res))
                     (when (gethash (dx (cons y (+ x 2))) table)
                       (incf res))
                     (when (gethash (dx (cons (+ y 1) (+ x 2))) table)
                       (incf res))
                     (when (gethash (dx (cons (+ y 2) (+ x 2))) table)
                       (incf res))
                     res))))
      (loop for (y . x) of-type (uint32 . uint32) being each hash-key of table
            do (when (< (+ y 2) h)
                 (when (< (+ x 2) w)
                   (incf (aref res (frob y x))))
                 (when (< (+ x 1) w)
                   (incf (aref res (frob y (- x 1)))))
                 (incf (aref res (frob y (- x 2)))))
               (when (< (+ y 1) h)
                 (when (< (+ x 2) w)
                   (incf (aref res (frob (- y 1) x))))
                 (when (< (+ x 1) w)
                   (incf (aref res (frob (- y 1) (- x 1)))))
                 (incf (aref res (frob (- y 1) (- x 2)))))
               (when (< (+ x 2) w)
                 (incf (aref res (frob (- y 2) x))))
               (when (< (+ x 1) w)
                 (incf (aref res (frob (- y 2) (- x 1)))))
               (incf (aref res (frob (- y 2) (- x 2)))))
      (loop for i from 1 to 9
            do (setf (aref res i) (/ (aref res i) i)))
      (println (- (* (- h 2) (- w 2))
                  (reduce #'+ res :start 1)))
      (loop for i from 1 to 9
            do (println (aref res i))))))

#-swank (main)


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

;; BEGIN_INSERTED_CONTENTS
;; DEFINE-INTEGER-PACK and DEFINE-CONS-PACK are so to say poor man's variants of
;; DEFSTRUCT. Both "structures" can only have slots of fixed unsigned
;; bytes. DEFINE-INTEGER-PACK handles the concatenated slots as UNSIGNED-BYTE
;; and DEFINE-CONS-PACK handles them as (CONS (UNSIGNED-BYTE 62) (UNSIGNED-BYTE
;; 62)).

;; Example:
;; The following form defines the type NODE as (UNSIGNED-BYTE 9):
;; (define-integer-pack node (slot1 3) (slot2 5) (slot3 1))
;; This macro in addition defines relevant utilities: NODE-SLOT1, NODE-SLOT2,
;; NODE-SLOT3, setters and getters, PACK-NODE, the constructor, and
;; WITH-UNPACKING-NODE, the destructuring-bind-style macro.
;;
;; DEFINE-CONS-PACK is almost the same as DEFINE-INTEGER-PACK though it will be
;; suitable for the total bits in the range [63, 124].

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defun %concat-name (&rest args)
    (if (cdr args)
        (format nil "~A-~A"
                (car args)
                (apply #'%concat-name (cdr args)))
        (car args)))

  (defun %concat+name+ (&rest args)
    (format nil "+~A+" (apply #'%concat-name args))))

(defmacro define-integer-pack (name &rest slot-descriptions)
  (assert slot-descriptions () "~A has no slots." name)
  (let* ((packer-name (intern (%concat-name "PACK" name)))
         (unpacker-macro-name (intern (%concat-name "WITH-UNPACKING" name)))
         (total-size 0)
         (slots (loop with position = 0
                      for (slot-name slot-size) in slot-descriptions
                      collect (progn (check-type slot-name symbol)
                                     (check-type slot-size (integer 1))
                                     (list slot-name slot-size position))
                      do (incf position slot-size)
                      finally (setq total-size position)))
         (revslots (reverse slots))
         (new-value (gensym "NEW-VALUE"))
         (tmp (gensym)))
    `(progn
       (deftype ,name () '(unsigned-byte ,total-size))
       ;; define most positive integer for every slot as constant
       ,@(loop for (slot-name slot-size _) in slots
               collect `(defconstant ,(intern (%concat+name+ "MAX" name slot-name))
                          (- (ash 1 ,slot-size) 1)))
       ;; setter and getter
       ,@(loop for (slot-name slot-size slot-position) in slots
               for accessor-name = (intern (%concat-name name slot-name))
               append `((declaim (inline ,accessor-name
                                         (setf ,accessor-name)))
                        (defun ,accessor-name (,name)
                          (declare (type ,name ,name))
                          (ldb (byte ,slot-size ,slot-position) ,name))
                        (defun (setf ,accessor-name) (,new-value ,name)
                          (declare (type ,name ,name))
                          (setf (ldb (byte ,slot-size ,slot-position) ,name) ,new-value))))
       ;; constructor
       (declaim (inline ,packer-name))
       (defun ,packer-name ,(loop for slot in slots collect (car slot))
         (declare ,@(loop for (slot-name slot-size _) in slots
                          collect `(type (unsigned-byte ,slot-size) ,slot-name )))
         (let ((,tmp ,(caar revslots)))
           (declare (type (unsigned-byte ,total-size) ,tmp))
           ,@(loop for (slot-name slot-size _) in (cdr revslots)
                   collect `(setq ,tmp (logxor ,slot-name
                                               (the (unsigned-byte ,total-size)
                                                    (ash ,tmp ,slot-size)))))
           ,tmp))
       ;; destructuring-bind-style macro
       (defmacro ,unpacker-macro-name (vars ,name &body body)
         (check-type vars list)
         (assert (= (length vars) ,(length slots)))
         `(let ((,',tmp ,,name))
            (declare (type (unsigned-byte ,,total-size) ,',tmp))
            (let* ,(loop for var in vars
                         for rest on ',slots
                         for (slot-name slot-size _) = (car rest)
                         collect `(,var
                                   (prog1 (the (unsigned-byte ,slot-size)
                                               (ldb (byte ,slot-size 0) ,',tmp))
                                     ,@(when (cdr rest)
                                         `((setq ,',tmp (ash ,',tmp ,(- slot-size))))))))
              ,@body))))))

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

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

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

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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

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

(define-integer-pack elm (station 20) (color 20) (dist 20))

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

#-swank (main)

Score : 600 points

Problem Statement

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

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

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

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

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

Constraints

2 \leq N \leq 10^5

0 \leq M \leq 2×10^5

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

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

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

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

Input

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

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

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

Sample Input 1

3 3
1 2 1
2 3 1
3 1 2

Sample Output 1

1

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

Sample Input 2

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

Sample Output 2

2

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

Sample Input 3

2 0

Sample Output 3

-1


(defun solve(a b c)
  (let* ((l (sort (list a b c) #'<=)))
    (if (some #'evenp l)
        0
        (* (first l) (second l)))))

(defun main()
  (let ((a (read))
        (b (read))
        (c (read)))
    (princ (solve a b c))))

(main)

Score : 200 points

Problem Statement

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

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

The union of all red blocks forms a rectangular parallelepiped.

The union of all blue blocks forms a rectangular parallelepiped.

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

Constraints

2≤A,B,C≤10^9

Input

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

A B C

Output

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

Sample Input 1

3 3 3

Sample Output 1

9

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

Sample Input 2

2 2 4

Sample Output 2

0

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

Sample Input 3

5 3 5

Sample Output 3

15

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


(defparameter *IN* (read-line))

(defparameter *A* (parse-integer (subseq *IN* 0 1)))
(defparameter *B* (parse-integer (subseq *IN* 2 3)))
(defparameter *C* (parse-integer (subseq *IN* 4 5)))

(defparameter *ANS* (if (= (or (mod *A* 2) (mod *B* 2) (mod *C* 2)) 0)
			0
			(min (* *A* *B*) (* *B* *C*) (* *C* *A*))))
(princ *ANS*)


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

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((h (read))
         (w (read))
         (plan (make-array (list h w) :element-type 'bit))
         (res1 (make-array (list h w) :element-type 'base-char :initial-element #\.))
         (res2 (make-array (list h w) :element-type 'base-char :initial-element #\.)))
    (dotimes (i h)
      (setf (aref res1 i 0) #\#)
      (when (evenp i)
        (dotimes (j w)
          (setf (aref res1 i j) #\#))))
    (dotimes (i h)
      (setf (aref res2 i (- w 1)) #\#)
      (when (oddp i)
        (dotimes (j w)
          (setf (aref res2 i j) #\#))))
    (dotimes (i h)
      (let ((line (read-line)))
        (dotimes (j w)
          (when (char= #\# (aref line j))
            (setf (aref res1 i j) #\#
                  (aref res2 i j) #\#)))))
    (let ((*print-escape* nil))
      (print-matrix res1 :separator "")
      (terpri)
      (print-matrix res2 :separator ""))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5 5
.....
.#.#.
.....
.#.#.
.....
"
    ".....
#####
#....
#####
.....

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

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

Score : 700 points

Problem Statement

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

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

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

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

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

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

Constraints

3≤H,W≤500

a_{ij} is # or ..

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

At least one of a_{ij} is #.

Input

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

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

Output

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

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

The following 1 line should be empty.

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

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

Sample Input 1

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

Sample Output 1

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

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

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

Sample Input 2

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

Sample Output 2

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

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

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


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

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (k (read))
         (k-1 (- k 1))
         ;; (graph (make-array n :element-type 'uint32 :initial-element 0))
         (revgraph (make-array n :element-type 'list :initial-element nil))
         (neighbors (make-array n :element-type 'bit :initial-element 0))
         (res 0))
    (dotimes (i n)
      (let ((a (- (read-fixnum) 1)))
        (if (zerop i)
            (unless (zerop a)
              (incf res))
            (push i (aref revgraph a)))
        (when (zerop a)
          (setf (aref neighbors i) 1))))
    #>neighbors
    (labels ((dfs (v parent)
               (let ((depth 0))
                 (dolist (child (aref revgraph v))
                   (unless (= child parent)
                     (maxf depth (+ 1 (dfs child v)))))
                 (assert (<= depth k-1))
                 (if (= depth k-1)
                     (progn
                       (unless (or (zerop v)
                                   (= (aref neighbors v) 1))
                         (incf res))
                       -1)
                     depth))))
      (dfs 0 -1)
      (println res))))

#-swank (main)

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

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

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

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

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

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

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

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

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

Score : 800 points

Problem Statement

There are N towns in Snuke Kingdom, conveniently numbered 1 through N.
Town 1 is the capital.

Each town in the kingdom has a Teleporter, a facility that instantly transports a person to another place.
The destination of the Teleporter of town i is town a_i (1≤a_i≤N).
It is guaranteed that one can get to the capital from any town by using the Teleporters some number of times.

King Snuke loves the integer K.
The selfish king wants to change the destination of the Teleporters so that the following holds:

Starting from any town, one will be at the capital after using the Teleporters exactly K times in total.

Find the minimum number of the Teleporters whose destinations need to be changed in order to satisfy the king's desire.

Constraints

2≤N≤10^5

1≤a_i≤N

One can get to the capital from any town by using the Teleporters some number of times.

1≤K≤10^9

Input

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

N K
a_1 a_2 ... a_N

Output

Print the minimum number of the Teleporters whose destinations need to be changed in order to satisfy King Snuke's desire.

Sample Input 1

3 1
2 3 1

Sample Output 1

2

Change the destinations of the Teleporters to a = (1,1,1).

Sample Input 2

4 2
1 1 2 2

Sample Output 2

0

There is no need to change the destinations of the Teleporters, since the king's desire is already satisfied.

Sample Input 3

8 2
4 1 2 3 1 2 3 4

Sample Output 3

3

For example, change the destinations of the Teleporters to a = (1,1,2,1,1,2,2,4).


(defun outer (l1 l2)
 (union (set-difference l1 l2)
        (set-difference l2 l1)))

(defun solve (l tl)
  (cond
    ((null l) (if (null tl) "Yes" "No"))
    (t (solve (cdr l) (outer tl (list (car l)))))))

(defun main ()
  (let ((str (read-line)))
    (princ (solve (loop :as c
                        :across str
                        :collect c)
                  '()))))

(main)

Score : 200 points

Problem Statement

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

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

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

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

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

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

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

Sample Input 2

hthth

Sample Output 2

No


(setq s(sort(concatenate'list(read-line))#'char<))
(princ(if(=(mod(length s)2)1)"No"(if(>(loop for i from 0 to(1-(/(length s)2))count(char/=(nth(* i 2)s)(nth(1+(* i 2))s)))0)"No""Yes")))


(defvar *b*)
(defvar *cache*)
(defvar *x*)

(defun binomial (n)
	(setf *b* (make-array (list n n)))
	(dotimes (i n)
		(setf (aref *b* 0 i) 0)
		(setf (aref *b* i i) 1))
	(loop :for i :from 1 :below n :do
		 (loop :for j :from 1 :below i :do
				(setf (aref *b* i j) (+ (aref *b* (1- i) (1- j)) (aref *b* (1- i) j))))))

(defun s (a k i)
	(cond ((< a 0) 0)
				((< k 0) 0)
				((zerop k) (if (zerop a) 1 0))
				((> i a) 0)
				((= i 51) 0)
				(t (let ((key (+ (* a 51 51) (* k 51) i)))
						 (if (aref *cache* key)
								 (aref *cache* key)
								 (let ((c (s a k (1+ i))))
									 (loop :for j :from 1 :to (aref *x* i) :do
											(incf c (* (aref *b* (1+ (aref *x* i)) (1+ j))
																 (s (- a (* i j)) (- k j) (1+ i)))))
									 (setf (aref *cache* key) c)
									 c))))))

(let ((n (read))
			(a (read)))
	(binomial (+ n 2))
	(setf *cache* (make-array (expt 51 4) :initial-element nil))
	(setf *x* (make-array 51 :initial-element 0))
	(loop :repeat n :do (incf (aref *x* (read))))
	(format t "~a~%" (loop :for i :from 1 :to n :sum (s (* a i) i 0))))

Score : 300 points

Problem Statement

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

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

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

Partial Score

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

Input

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

N A
x_1 x_2 ... x_N

Output

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

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

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

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

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

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

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

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

Sample Output 4

8589934591

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


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; ARRAY-ELEMENT-TYPE is not constant-folded on SBCL version earlier than
;;; 1.5.0. See
;;; https://github.com/sbcl/sbcl/commit/9f0d12e7ab961828931d01c0b2a76a5885ad35d2
;;;

(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:deftransform array-element-type ((array))
    (let ((type (sb-c::lvar-type array)))
      (flet ((element-type (type)
               (and (sb-c::array-type-p type)
                    (sb-int:neq (sb-kernel::array-type-specialized-element-type type) sb-kernel:*wild-type*)
                    (sb-kernel:type-specifier (sb-kernel::array-type-specialized-element-type type)))))
        (cond ((let ((type (element-type type)))
                 (and type
                      `',type)))
              ((sb-kernel:union-type-p type)
               (let (result)
                 (loop for type in (sb-kernel:union-type-types type)
                       for et = (element-type type)
                       unless (and et
                                   (if result
                                       (equal result et)
                                       (setf result et)))
                       do (sb-c::give-up-ir1-transform))
                 `',result))
              ((sb-kernel:intersection-type-p type)
               (loop for type in (sb-kernel:intersection-type-types type)
                     for et = (element-type type)
                     when et
                     return `',et
                     finally (sb-c::give-up-ir1-transform)))
              (t
               (sb-c::give-up-ir1-transform)))))))

;;;
;;; Compute inversion number by merge sort
;;;

(declaim (inline %merge-count))
(defun %merge-count (l mid r source-vec dest-vec predicate)
  (declare ((integer 0 #.array-total-size-limit) l mid r)
           (function predicate))
  (loop with count of-type (integer 0 #.most-positive-fixnum) = 0
        with i = l
        with j = mid
        for idx from l
        when (= i mid)
        do (loop for j from j below r
                 for idx from idx
                 do (setf (aref dest-vec idx)
                          (aref source-vec j))
                 finally (return-from %merge-count count))
        when (= j r)
        do (loop for i from i below mid
                 for idx from idx
                 do (setf (aref dest-vec idx)
                          (aref source-vec i))
                 finally (return-from %merge-count count))
        do (if (funcall predicate
                        (aref source-vec j)
                        (aref source-vec i))
               (setf (aref dest-vec idx) (aref source-vec j)
                     j (1+ j)
                     count (+ count (- mid i)))
               (setf (aref dest-vec idx) (aref source-vec i)
                     i (1+ i)))))

(defmacro with-fixnum+ (form)
  (let ((fixnum+ '(integer 0 #.most-positive-fixnum)))
    `(the ,fixnum+
          ,(reduce (lambda (f1 f2)`(,(car form)
                                   (the ,fixnum+ ,f1)
                                   (the ,fixnum+ ,f2)))
	           (cdr form)))))

(declaim (inline %calc-by-insertion-sort!))
(defun %calc-by-insertion-sort! (vec predicate l r)
  (declare (function predicate)
           ((integer 0 #.array-total-size-limit) l r))
  (loop with inv-count of-type (integer 0 #.most-positive-fixnum) = 0
        for end from (+ l 1) below r
        do (loop for i from end above l
                 while (funcall predicate (aref vec i) (aref vec (- i 1)))
                 do (rotatef (aref vec (- i 1)) (aref vec i))
                    (incf inv-count))
        finally (return inv-count)))

;; NOTE: This function is slow on SBCL version earlier than 1.5.0 as
;; constant-folding of ARRAY-ELEMENT-TYPE doesn't work. Use
;; array-element-type.lisp if necessary.
(declaim (inline calc-inversion-number!))
(defun calc-inversion-number! (vector predicate &key (start 0) end)
  "Calculates the inversion number of VECTOR w.r.t. the strict order
PREDICATE. This function sorts VECTOR as a side effect."
  (declare (vector vector)
           (function predicate))
  (let ((end (or end (length vector))))
    (declare ((integer 0 #.array-total-size-limit) start end))
    (assert (<= start end))
    (let ((buffer (make-array end :element-type (array-element-type vector))))
      (labels
          ((recur (l r merge-to-vec1-p)
             (declare (optimize (safety 0))
                      ((integer 0 #.array-total-size-limit) l r))
             (cond ((= l r) 0)
                   ((= (+ l 1) r)
                    (unless merge-to-vec1-p
                      (setf (aref buffer l) (aref vector l)))
                    0)
                   ;; It is faster to use insertion sort. I don't adopt it
                   ;; by default, however, because that makes it hard to
                   ;; change the code to fit some special settings.
                   ;; ((and (<= (- r l) 24) merge-to-vec1-p)
                   ;;  (%calc-by-insertion-sort! vector predicate l r))
                   (t
                    (let ((mid (floor (+ l r) 2)))
                      (with-fixnum+
                          (+ (recur l mid (not merge-to-vec1-p))
                             (recur mid r (not merge-to-vec1-p))
                             (if merge-to-vec1-p
                                 (%merge-count l mid r buffer vector predicate)
                                 (%merge-count l mid r vector buffer predicate)))))))))
        (recur start end t)))))

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

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

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

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

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

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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare (inline sort))
  (let* ((n (read))
         (as (make-array n :element-type 'uint32)))
    (declare (uint32 n))
    (dotimes (i n) (setf (aref as i) (read-fixnum)))
    (let ((sorted-as (sort (copy-seq as) #'<))
          (parities (make-array n :element-type 'bit :initial-element 0))
          (seq1 (make-array n :element-type 'uint32 :initial-element 0))
          (seq2 (make-array n :element-type 'uint32 :initial-element 0)))
      (dotimes (i n)
        (when (oddp (bisect-left sorted-as (aref as i)))
          (setf (aref parities i) 1)))
      (let ((index0 0)
            (index1 1))
        (dotimes (i n)
          (if (zerop (aref parities i))
              (progn (setf (aref seq1 i) index0)
                     (incf index0 2))
              (progn (setf (aref seq1 i) index1)
                     (incf index1 2)))))
      (let ((index0 1)
            (index1 0))
        (dotimes (i n)
          (if (zerop (aref parities i))
              (progn (setf (aref seq2 i) index0)
                     (incf index0 2))
              (progn (setf (aref seq2 i) index1)
                     (incf index1 2)))))
      (dbg seq1 seq2)
      (println (min (calc-inversion-number! seq1 #'<)
                    (if (evenp n)
                        (calc-inversion-number! seq2 #'<)
                        most-positive-fixnum))))))

#-swank (main)

Score : 600 points

Problem Statement

Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 ≦ i ≦ N) element of the sequence is a_i. The elements are pairwise distinct.
He is sorting this sequence in increasing order.
With supernatural power, he can perform the following two operations on the sequence in any order:

Operation 1: choose 2 consecutive elements, then reverse the order of those elements.

Operation 2: choose 3 consecutive elements, then reverse the order of those elements.

Snuke likes Operation 2, but not Operation 1. Find the minimum number of Operation 1 that he has to perform in order to sort the sequence in increasing order.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9

If i ≠ j, then A_i ≠ A_j.

All input values are integers.

Input

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

N
A_1
:
A_N

Output

Print the minimum number of times Operation 1 that Snuke has to perform.

Sample Input 1

4
2
4
3
1

Sample Output 1

1

The given sequence can be sorted as follows:

First, reverse the order of the last three elements. The sequence is now: 2,1,3,4.

Then, reverse the order of the first two elements. The sequence is now: 1,2,3,4.

In this sequence of operations, Operation 1 is performed once. It is not possible to sort the sequence with less number of Operation 1, thus the answer is 1.

Sample Input 2

5
10
8
5
3
2

Sample Output 2

0