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

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (declare #.OPT)
  (macrolet ((%read-byte ()
               `(the (unsigned-byte 8)
                     #+swank (char-code (read-char in nil #\Nul))
                     #-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
    (let* ((minus nil)
           (result (loop (let ((byte (%read-byte)))
                           (cond ((<= 48 byte 57)
                                  (return (- byte 48)))
                                 ((zerop byte) ; #\Nul
                                  (error "Read EOF or #\Nul."))
                                 ((= byte #.(char-code #\-))
                                  (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))))))))

(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (sup)
  "Returns a simple-bit-vector of length SUP, whose (0-based) i-th bit is 1 if i
is prime and 0 otherwise.

Example: (make-prime-table 10) => #*0011010100"
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-array sup :element-type 'bit :initial-element 0))
        (sup/64 (ceiling sup 64)))
    ;; special treatment for p = 2
    (dotimes (i sup/64)
      (setf (sb-kernel:%vector-raw-bits table i) #xAAAAAAAAAAAAAAAA))
    (setf (sbit table 1) 0
          (sbit table 2) 1)
    ;; p >= 3
    (loop for p from 3 to (+ 1 (isqrt (- sup 1))) by 2
          when (= 1 (sbit table p))
          do (loop for composite from (* p p) below sup by p
                   do (setf (sbit table composite) 0)))
    table))

;; FIXME: Currently the element type of the resultant vector is (UNSIGNED-BYTE 62).
(declaim (ftype (function * (values (simple-array (integer 0 #.most-positive-fixnum) (*))
                                    simple-bit-vector
                                    &optional))
                make-prime-sequence))
(defun make-prime-sequence (sup)
  "Returns the ascending sequence of primes smaller than SUP."
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-prime-table sup)))
    (let* ((length (count 1 table))
           (result (make-array length :element-type '(integer 0 #.most-positive-fixnum)))
           (index 0))
      (declare ((integer 0 #.most-positive-fixnum) length))
      (loop for x below sup
            when (= 1 (sbit table x))
            do (setf (aref result index) x)
               (incf index))
      (values result table))))

(defstruct (prime-data (:constructor %make-prime-data (seq table)))
  (seq nil :type (simple-array (integer 0 #.most-positive-fixnum) (*)))
  (table nil :type simple-bit-vector))

(defun make-prime-data (sup)
  (multiple-value-call #'%make-prime-data (make-prime-sequence sup)))

(declaim (inline factorize)
         (ftype (function * (values list &optional)) factorize))
(defun factorize (x prime-data)
  "Returns the associative list of prime factors of X, which is composed
of (<prime> . <exponent>). E.g. (factorize 40 <prime-table>) => '((2 . 3) (5
. 1)).

- Any numbers beyond the range of PRIME-DATA are regarded as prime.
- The returned list is in descending order w.r.t. prime factors."
  (declare (integer x))
  (setq x (abs x))
  (when (<= x 1)
    (return-from factorize nil))
  (let ((prime-seq (prime-data-seq prime-data))
        result)
    (loop for prime of-type unsigned-byte across prime-seq
          do (when (= x 1)
               (return-from factorize result))
             (loop for exponent of-type (integer 0 #.most-positive-fixnum) from 0
                   do (multiple-value-bind (quot rem) (floor x prime)
                        (if (zerop rem)
                            (setf x quot)
                            (progn
                              (when (> exponent 0)
                                (push (cons prime exponent) result))
                              (loop-finish))))))
    (if (= x 1)
        result
        (cons (cons x 1) 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)

(defun rho (n)
  (declare #.OPT
           (uint62 n))
  (let ((m (ash 1 (integer-length n))))
    (macrolet ((f (x) `(let ((xx ,x)) (mod (+ c (* xx xx)) n))))
      (loop for c from 1 below 99
            for y of-type uint62 = 2
            for r of-type uint62 = 1
            for q of-type uint62 = 1
            for g of-type uint62 = 1
            for ys of-type uint62 = y
            for x of-type uint62 = y
            do (loop while (= g 1)
                     do (setq x y)
                        (dotimes (_ r)
                          (setq y (f y)))
                        (let ((k 0))
                          (declare (uint62 k))
                          (loop while (and (< k r) (= g 1))
                                do (setq ys y)
                                   (dotimes (_ (min m (- r k)))
                                     (setq y (f y)
                                           q (mod (* q (abs (- x y))) n)))
                                   (setq g (gcd q n))
                                   (incf k m)))
                        (setq r (ash r 1)))
               (when (= g n)
                 (loop while (= g 1)
                       do (setq ys (f ys)
                                g (gcd (abs (- x ys)) n))))
               (when (< g n)
                 (return g))))))

(defconstant +max+ 2300)
(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (pdata (make-prime-data +max+))
         (table (make-hash-table :test #'equal))
         (null-count 0))
    (declare (uint32 n null-count))
    (labels
        ((%factorize (s)
           (let ((factors (factorize s pdata)))
             (if (null factors)
                 nil
                 (let ((largest (caar factors)))
                   (declare (uint62 largest))
                   (if (< largest +max+)
                       factors
                       (let ((sqrt (isqrt largest)))
                         (if (= (* sqrt sqrt) largest)
                             (cons (cons sqrt 2) (cdr factors))
                             factors)))))))
         (add (factors)
           (cond ((null factors)
                  (incf null-count))
                 ((= 1 (cdar factors))
                  (if (gethash factors table)
                      (incf (car (gethash factors table)))
                      (setf (gethash factors table) (cons 1 0))))
                 (t
                  (let ((factors (loop for (p . exp) of-type (uint62 . uint62) in factors
                                       collect (cons p (- 3 exp)))))
                    (if (gethash factors table)
                        (incf (cdr (gethash factors table)))
                        (setf (gethash factors table) (cons 0 1))))))))
      (dotimes (i n)
        (let* ((s (read-fixnum))
               (factors (loop for (p . exp) of-type (uint62 . uint62) in (%factorize s)
                              unless (zerop (mod exp 3))
                              collect (cons p (mod exp 3)))))
          (add factors)))
      (println
       (+ (min null-count 1)
          (loop for (count1 . count2) being each hash-value of table
                sum (max count1 count2)))))))

#-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 "8
1
2
3
4
5
6
7
8
"
    "6
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
2
4
8
16
32
64
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10
1
10
100
1000000007
10000000000
1000000009
999999999
999
999
999
"
    "9
")))

Score : 1100 points

Problem Statement

Snuke got positive integers s_1,...,s_N from his mother, as a birthday present. There may be duplicate elements.

He will circle some of these N integers. Since he dislikes cubic numbers, he wants to ensure that if both s_i and s_j (i ≠ j) are circled, the product s_is_j is not cubic. For example, when s_1=1,s_2=1,s_3=2,s_4=4, it is not possible to circle both s_1 and s_2 at the same time. It is not possible to circle both s_3 and s_4 at the same time, either.

Find the maximum number of integers that Snuke can circle.

Constraints

1 ≦ N ≦ 10^5

1 ≦ s_i ≦ 10^{10}

All input values are integers.

Input

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

N
s_1
:
s_N

Output

Print the maximum number of integers that Snuke can circle.

Sample Input 1

8
1
2
3
4
5
6
7
8

Sample Output 1

6

Snuke can circle 1,2,3,5,6,7.

Sample Input 2

6
2
4
8
16
32
64

Sample Output 2

3

Sample Input 3

10
1
10
100
1000000007
10000000000
1000000009
999999999
999
999
999

Sample Output 3

9


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

(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (sup)
  "Returns a simple-bit-vector of length SUP, whose (0-based) i-th bit is 1 if i
is prime and 0 otherwise.

Example: (make-prime-table 10) => #*0011010100"
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-array sup :element-type 'bit :initial-element 0))
        (sup/64 (ceiling sup 64)))
    ;; special treatment for p = 2
    (dotimes (i sup/64)
      (setf (sb-kernel:%vector-raw-bits table i) #xAAAAAAAAAAAAAAAA))
    (setf (sbit table 1) 0
          (sbit table 2) 1)
    ;; p >= 3
    (loop for p from 3 to (+ 1 (isqrt (- sup 1))) by 2
          when (= 1 (sbit table p))
          do (loop for composite from (* p p) below sup by p
                   do (setf (sbit table composite) 0)))
    table))

;; FIXME: Currently the element type of the resultant vector is (UNSIGNED-BYTE 62).
(declaim (ftype (function * (values (simple-array (integer 0 #.most-positive-fixnum) (*))
                                    simple-bit-vector
                                    &optional))
                make-prime-sequence))
(defun make-prime-sequence (sup)
  "Returns the ascending sequence of primes smaller than SUP."
  (declare (optimize (speed 3) (safety 0)))
  (check-type sup (integer 2 (#.array-total-size-limit)))
  (let ((table (make-prime-table sup)))
    (let* ((length (count 1 table))
           (result (make-array length :element-type '(integer 0 #.most-positive-fixnum)))
           (index 0))
      (declare ((integer 0 #.most-positive-fixnum) length))
      (loop for x below sup
            when (= 1 (sbit table x))
            do (setf (aref result index) x)
               (incf index))
      (values result table))))

(defstruct (prime-data (:constructor %make-prime-data (seq table)))
  (seq nil :type (simple-array (integer 0 #.most-positive-fixnum) (*)))
  (table nil :type simple-bit-vector))

(defun make-prime-data (sup)
  (multiple-value-call #'%make-prime-data (make-prime-sequence sup)))

(declaim (inline factorize)
         (ftype (function * (values list &optional)) factorize))
(defun factorize (x prime-data)
  "Returns the associative list of prime factors of X, which is composed
of (<prime> . <exponent>). E.g. (factorize 40 <prime-table>) => '((2 . 3) (5
. 1)).

- Any numbers beyond the range of PRIME-DATA are regarded as prime.
- The returned list is in descending order w.r.t. prime factors."
  (declare (integer x))
  (setq x (abs x))
  (when (<= x 1)
    (return-from factorize nil))
  (let ((prime-seq (prime-data-seq prime-data))
        result)
    (loop for prime of-type unsigned-byte across prime-seq
          do (when (= x 1)
               (return-from factorize result))
             (loop for exponent of-type (integer 0 #.most-positive-fixnum) from 0
                   do (multiple-value-bind (quot rem) (floor x prime)
                        (if (zerop rem)
                            (setf x quot)
                            (progn
                              (when (> exponent 0)
                                (push (cons prime exponent) result))
                              (loop-finish))))))
    (if (= x 1)
        result
        (cons (cons x 1) 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))
         (pdata (make-prime-data 4000))
         (table (make-hash-table :test #'equal))
         (null-count 0))
    (declare (uint32 n null-count))
    (labels ((add (factors)
               (cond ((null factors)
                      (incf null-count))
                     ((= 1 (cdar factors))
                      (if (gethash factors table)
                          (incf (car (gethash factors table)))
                          (setf (gethash factors table) (cons 1 0))))
                     (t
                      (assert (= 2 (cdar factors)))
                      (let ((factors (loop for (p . exp) of-type (uint62 . uint62) in factors
                                           collect (cons p (- 3 exp)))))
                        (if (gethash factors table)
                            (incf (cdr (gethash factors table)))
                            (setf (gethash factors table) (cons 0 1))))))))
      (dotimes (i n)
        (let* ((s (read-fixnum))
               (factors (loop for (p . exp) of-type (uint62 . uint62) in (factorize s pdata)
                              unless (zerop (mod exp 3))
                              collect (cons p (mod exp 3)))))
          (add factors)))
      #>null-count
      (println
       (+ (min null-count 1)
          (loop for (count1 . count2) being each hash-value of table
                sum (max count1 count2)))))))

#-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 "8
1
2
3
4
5
6
7
8
"
    "6
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
2
4
8
16
32
64
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "10
1
10
100
1000000007
10000000000
1000000009
999999999
999
999
999
"
    "9
")))

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.


;;; body

(defconstant +inf+ 10000000)

(defun main ()
  (let ((n (read)))
    (declare ((unsigned-byte 8) n))
    (let ((a (loop repeat n collect (read))))
      (declare (list a))
      (let ((res +inf+))
        (declare (fixnum res))
        (loop for y of-type (signed-byte 16) from -100 to 100 do
             (let ((tmp (reduce #'+
                                (mapcar (lambda (x)
                                          (expt (- x y) 2))
                                        a))))
               (declare (fixnum tmp))
               (when (< tmp res)
                 (setq res tmp))))
        (format t "~a~&" res)))))

#-swank (main)

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

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

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.


Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

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

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


(let ((s (concatenate 'list (read-line)))
      (lst '()))

  (loop for i in s
        if (char= i #\0) do (push "0" lst)
        else if (char= i #\1) do (push "1" lst)
        else do (if (not (equal lst '())) (pop lst)))

  (format t "~a~%" (reverse (apply #'concatenate 'string lst))))

Score : 200 points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

1 ≦ |s| ≦ 10 (|s| denotes the length of s)

s consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

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

s

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.


(let* ((str (read-line))
       (ans nil))
  (map nil (lambda (n) (cond ((char= n #\0) (push #\0 ans))
                             ((char= n #\1) (push #\1 ans))
                             ((char= n #\B) (pop ans)))) str)
  (princ (concatenate 'string (reverse ans))))


(let* ((n (read))
       (lst (loop :repeat n :collect (read))))
  (princ (loop :for a :from (reduce #'min lst) :upto (reduce #'max lst)
               :minimize (reduce #'+ (mapcar (lambda (k) (expt (- a k) 2)) lst)))))


(defun solve (s)
  (cond ((< (length s) 2) (format t "~D ~D~%" -1 -1) (return-from solve))
        ((= (length s) 2) (if (eq (aref s 0) (aref s 1))
                            (progn (format t "~D ~D~%" 1 2) (return-from solve))
                            (progn (format t "~D ~D~%" -1 -1) (return-from solve)))
                          )
        (t
          (loop :for c :across s :and i :from 0 :below (- (length s) 2) :do
                (cond ((eq (aref s i) (aref s (+ i 1)))
                       (format t "~D ~D~%" (+ i 1) (+ i 2))
                       (return-from solve))
                      ((eq (aref s i) (aref s (+ i 2)))
                       (format t "~D ~D~%" (+ i 1) (+ i 3))
                       (return-from solve))
                      ))))
  (format t "~D ~D~%" -1 -1))

(defun main()
  (let ((s (read-line)))
    (solve s)
    ))

(main)

Score : 400 points

Problem Statement

Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both voodoo and melee are unbalanced, while neither noon nor a is.

You are given a string s consisting of lowercase letters. Determine if there exists a (contiguous) substring of s that is unbalanced. If the answer is positive, show a position where such a substring occurs in s.

Constraints

2 ≦ |s| ≦ 10^5

s consists of lowercase letters.

Partial Score

200 points will be awarded for passing the test set satisfying 2 ≦ N ≦ 100.

Input

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

s

Output

If there exists no unbalanced substring of s, print -1 -1.

If there exists an unbalanced substring of s, let one such substring be s_a s_{a+1} ... s_{b} (1 ≦ a < b ≦ |s|), and print a b. If there exists more than one such substring, any of them will be accepted.

Sample Input 1

needed

Sample Output 1

2 5

The string s_2 s_3 s_4 s_5 = eede is unbalanced. There are also other unbalanced substrings. For example, the output 2 6 will also be accepted.

Sample Input 2

atcoder

Sample Output 2

-1 -1

The string atcoder contains no unbalanced substring.


(let* ((a (read))
       (b (read)))
  (cond ((<= a 0 b) (princ "Zero"))
        ((or (<= 0 a b) (evenp (+ a b))) (princ "Positive"))
        ((and (<= a b 0) (oddp (+ a b))) (princ "Negative"))))

Problem Statement

You are given two integers a and b (a≤b). Determine if the product of the integers a, a+1, …, b is positive, negative or zero.

Constraints

a and b are integers.

-10^9≤a≤b≤10^9

Partial Score

In test cases worth 100 points, -10≤a≤b≤10.

Input

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

a b

Output

If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero.

Sample Input 1

1 3

Sample Output 1

Positive

1×2×3=6 is positive.

Sample Input 2

-3 -1

Sample Output 2

Negative

(-3)×(-2)×(-1)=-6 is negative.

Sample Input 3

-1 1

Sample Output 3

Zero

(-1)×0×1=0.


(let ((a (read))
			(b (read)))
	(format t "~a~%"
					(cond ((> a 0) "Positive")
								((> b 0) "Zero")
								((zerop (mod a 2)) "Positive")
								(t "Negative"))))


(defun solve (a b)
  (cond ((<= a 0 b) "Zero")
        ((> a 0) "Positive")
        ((evenp (+ a b)) "Negative")
        ((oddp (+ a b)) "Positive")))

(princ (solve (read) (read)))
(terpri)


(defun solve (a b)
  (cond ((or (<= b 0 a) (<= a 0 b)) "Zero")
        ((> a 0) "Positive")
        ((evenp (+ a b)) "Negative")))

(princ (solve (read) (read)))
(terpri)


(let* ((n (read))
       (m (read))
       (x (make-array m))
       (y (make-array m))
       (w (make-array n :initial-element 1))
       (red (make-array n :initial-element nil)))
  (dotimes (i m)
    (setf (aref x i) (read)
          (aref y i) (read)))
  (setf (aref red 0) t)
  (dotimes (i m)
    (let ((xi (1- (aref x i)))
          (yi (1- (aref y i))))
      (if (aref red xi)
          (setf (aref red yi) t))
      (decf (aref w xi))
      (incf (aref w yi))
      (if (zerop (aref w xi))
        (setf (aref red xi) nil))))
    (format t "~A~%" (loop for ri across red unless (null ri) count ri)))

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

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

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


(let ((i (make-array 11)))
    (incf (aref i (read)))
    (incf (aref i (read)))
    (incf (aref i (read)))
    (if (and (= (aref i 5) 2) (= (aref i 7) 1))
        (princ "YES")
        (princ "NO")
    )
)

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

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

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


(format t "~a~%"
        (if (equal '(5 5 7)
                   (sort (list (read) (read) (read)) #'<))
            "YES"
            "NO"))


(defparameter *mod* 1000000007)

(defun modExpt (a e m)
  (let ((res 1) (bit_str (format nil "~B" e)))
    (loop :for c :across bit_str :do
          (if (eq c #\0)
            (setq res (mod (* res res) m))
            (setq res (mod (* (mod (* res res) m) a) m))
            )
          )
    res))

(defun main ()
  (let* ((h (read)) (w (read)) (a (read)) (b (read))
         (fact_table (make-array (- (+ h w) 1) :initial-element 1))
         (inv_fact_table (make-array (- (+ h w) 1) :initial-element 1))
         (result 0))
    (loop :for i :from 2 :below (- (+ h w) 1) :do
          (setf (aref fact_table i) (mod (* (aref fact_table (- i 1)) i) *mod*)))

    (loop :for i :below (- (+ h w) 1) :do
          (setf (aref inv_fact_table i) (modExpt (aref fact_table i) (- *mod* 2) *mod*)))

    (defun comb (n r m)
      (mod (* (mod (* (aref fact_table n) (aref inv_fact_table r)) m) (aref inv_fact_table (- n r))) m))

    (loop :for i :from b :upto (- w 1) :do
          (setq result (+ result
                          (* (comb (- (+ (- h a) i) 1) (- (- h a) 1) *mod*)
                             (comb (- (- (+ w a) i) 2) (- a 1) *mod*))))
          )
    (setq result (mod result *mod*))
    (princ result) (princ #\newline)
    ))

(main)

Score : 400 points

Problem Statement

We have a large square grid with H rows and W columns.
Iroha is now standing in the top-left cell.
She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.

However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there are A×B forbidden cells.) There is no restriction on entering the other cells.

Find the number of ways she can travel to the bottom-right cell.

Since this number can be extremely large, print the number modulo 10^9+7.

Constraints

1 ≦ H, W ≦ 100,000

1 ≦ A < H

1 ≦ B < W

Input

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

H W A B

Output

Print the number of ways she can travel to the bottom-right cell, modulo 10^9+7.

Sample Input 1

2 3 1 1

Sample Output 1

2

We have a 2×3 grid, but entering the bottom-left cell is forbidden. The number of ways to travel is two: "Right, Right, Down" and "Right, Down, Right".

Sample Input 2

10 7 3 4

Sample Output 2

3570

There are 12 forbidden cells.

Sample Input 3

100000 100000 99999 99999

Sample Output 3

1

Sample Input 4

100000 100000 44444 55555

Sample Output 4

738162020


(let* ((n (read))
       (ans 0))
  (defun f (lst)
    (if (cdr lst)
        (progn (setf ans (+ ans (second lst))) (f (cddr lst)))))
  (f (sort (loop :repeat (* 2 n) :collect (read)) #'>))
  (princ ans))

Score : 200 points

Problem Statement

Snuke is having a barbeque party.

At the party, he will make N servings of Skewer Meal.

Example of a serving of Skewer Meal

He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i.
Also, he has an infinite supply of ingredients.

To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.

What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?

Constraints

1≦N≦100

1≦L_i≦100

For each i, L_i is an integer.

Input

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

N
L_1 L_2 ... L_{2N}

Output

Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.

Sample Input 1

2
1 3 1 2

Sample Output 1

3

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3.

Sample Input 2

5
100 1 2 3 14 15 58 58 58 29

Sample Output 2

135


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

;; BEGIN_INSERTED_CONTENTS
(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;
(defconstant +inf+ #xffffffff)
(defun max2 (list)
  (let ((max -1)
        (max2 -1))
    (assert (cdr list))
    (dolist (x list)
      (cond ((>= x max)
             (setq max2 max max x))
            ((>= x max2)
             (setq max2 x))))
    (values max max2)))

(defun main ()
  (let* ((n (read))
         (k (read))
         (edges (make-array (- n 1) :element-type 'list))
         (graph (make-array n :element-type 'list :initial-element nil)))
    (dotimes (i (- n 1))
      (let ((a (- (read) 1))
            (b (- (read) 1)))
        (setf (aref edges i) (cons a b))
        (push a (aref graph b))
        (push b (aref graph a))))
    (let ((k/2 (floor k 2))
          (res +inf+)
          (dists (make-array n :element-type 'uint32)))
      (labels ((fill-dists (v parent depth)
                 (setf (aref dists v) depth)
                 (dolist (child (aref graph v))
                   (unless (= child parent)
                     (fill-dists child v (+ depth 1)))))
               (get-max-depth (v parent)
                 (let ((res (aref dists v)))
                   (dolist (child (aref graph v))
                     (unless (= child parent)
                       (maxf res (get-max-depth child v))))
                   res)))
        (if (evenp k)
            (dotimes (root n)
              (when (cdr (aref graph root))
                (fill dists +inf+)
                (fill-dists root -1 0)
                (let* ((branch-depths (loop for child in (aref graph root)
                                            collect (get-max-depth child root))))
                  (dbg root dists branch-depths)
                  (multiple-value-bind (max max2) (max2 branch-depths)
                    (dbg max max2)
                    (when (>= max2 k/2)
                      (minf res (count-if (lambda (d) (> d k/2)) dists)))))))
            (loop
              for (r1 . r2) across edges
              when (and (car (aref graph r1))
                        (car (aref graph r2)))
              do (fill dists +inf+)
                 (fill-dists r1 r2 0)
                 (fill-dists r2 r1 0)
                 #>dists
                 (let* ((branch-depths1 (cons 0 (loop for child in (aref graph r1)
                                                      unless (= child r2)
                                                      collect (get-max-depth child r1))))
                        (branch-depths2 (cons 0 (loop for child in (aref graph r2)
                                                      unless (= child r1)
                                                      collect (get-max-depth child r2)))))
                   (dbg branch-depths1 branch-depths2)
                   (let ((max-depth1 (reduce #'max branch-depths1))
                         (max-depth2 (reduce #'max branch-depths2)))
                     (when (>= (min max-depth1 max-depth2) k/2)
                       (minf res (count-if (lambda (x) (> x k/2)) dists))))))))
      (println
       (if (= res +inf+)
           0
           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 "6 2
1 2
3 2
4 2
1 6
5 6
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6 5
1 2
3 2
4 2
1 6
5 6
"
    "0
")))

Score : 600 points

Problem Statement

Given an undirected tree, let the distance between vertices u and v be the
number of edges on the simple path from u to v.
The diameter of a tree is the maximum among the distances between any two vertices.
We will call a tree good if and only if its diameter is at most K.

You are given an undirected tree with N vertices numbered 1 through N.
For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i.

You want to remove zero or more vertices from the tree, so that the resulting tree is good.
When a vertex is removed, all incident edges will also be removed.
The resulting graph must be connected.

Find the minimum number of vertices that you need to remove in order to produce a good tree.

Constraints

2≦N≦2000

1≦K≦N-1

1≦A_i≦N, 1≦B_i≦N

The graph defined by A_i and B_i is a tree.

Input

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

N K
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}

Output

Print the minimum number of vertices that you need to remove in order to produce a good tree.

Sample Input 1

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

Sample Output 1

2

The tree is shown below. Removing vertices 5 and 6 will result in a good tree with the diameter of 2.

Sample Input 2

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

Sample Output 2

0

Since the given tree is already good, you do not need to remove any vertex.


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

;; BEGIN_INSERTED_CONTENTS
(macrolet ((def (name fname)
             `(define-modify-macro ,name (new-value) ,fname)))
  (def minf min)
  (def maxf max)
  (def mulf *)
  (def divf /)
  (def iorf logior)
  (def xorf logxor)
  (def andf logand))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;
(defconstant +inf+ #xffffffff)
(defun max2 (list)
  (let ((max -1)
        (max2 -1))
    (assert (cdr list))
    (dolist (x list)
      (cond ((>= x max)
             (setq max2 max max x))
            ((>= x max2)
             (setq max2 x))))
    (values max max2)))

(defun main ()
  (let* ((n (read))
         (k (read))
         (edges (make-array (- n 1) :element-type 'list))
         (graph (make-array n :element-type 'list :initial-element nil)))
    (dotimes (i (- n 1))
      (let ((a (- (read) 1))
            (b (- (read) 1)))
        (setf (aref edges i) (cons a b))
        (push a (aref graph b))
        (push b (aref graph a))))
    (let ((k/2 (floor k 2))
          (res +inf+)
          (dists (make-array n :element-type 'uint32)))
      (labels ((fill-dists (v parent depth)
                 (setf (aref dists v) depth)
                 (dolist (child (aref graph v))
                   (unless (= child parent)
                     (fill-dists child v (+ depth 1)))))
               (get-max-depth (v parent)
                 (let ((res (aref dists v)))
                   (dolist (child (aref graph v))
                     (unless (= child parent)
                       (maxf res (get-max-depth child v))))
                   res)))
        (if (evenp k)
            (dotimes (root n)
              (when (cdr (aref graph root))
                (fill dists +inf+)
                (fill-dists root -1 0)
                (let* ((branch-depths (loop for child in (aref graph root)
                                            collect (get-max-depth child root))))
                  (dbg root dists branch-depths)
                  (multiple-value-bind (max max2) (max2 branch-depths)
                    (dbg max max2)
                    (when (>= max2 k/2)
                      (minf res (count-if (lambda (d) (> d k/2)) dists)))))))
            (loop
              for (r1 . r2) across edges
              do (fill dists +inf+)
                 (fill-dists r1 r2 0)
                 (fill-dists r2 r1 0)
              (dbg r1 r2 dists)
                 (let* ((branch-depths1 (loop for child in (aref graph r1)
                                              unless (= child r2)
                                              collect (get-max-depth child r1)))
                        (branch-depths2 (loop for child in (aref graph r2)
                                              unless (= child r1)
                                              collect (get-max-depth child r2))))
                   (dbg branch-depths1 branch-depths2)
                   (when (and branch-depths1 branch-depths2)
                     (let ((max-depth1 (reduce #'max branch-depths1))
                           (max-depth2 (reduce #'max branch-depths2)))
                       (when (>= (min max-depth1 max-depth2) k/2)
                         (minf res (count-if (lambda (x) (> x k/2)) dists)))))))))
      (println
       (if (= res +inf+)
           0
           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 "6 2
1 2
3 2
4 2
1 6
5 6
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6 5
1 2
3 2
4 2
1 6
5 6
"
    "0
")))


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

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  (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))))))))

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

;;;
;;; Diameter of tree
;;;

(defun find-diameter (graph)
  "Finds a diameter of a tree. Returns three values: the length of the diameter
and its two ends."
  (declare ((array list (*)) graph))
  (let ((end 0)
        (max-depth 0))
    (assert (> (length graph) 0))
    (labels ((traverse (v parent depth)
               (declare ((integer 0 #.array-total-size-limit) v parent depth))
               (when (> depth max-depth)
                 (setq max-depth depth
                       end v))
               (dolist (child (aref graph v))
                 (declare ((integer 0 #.most-positive-fixnum) child))
                 (unless (= child parent)
                   (traverse child v (+ depth 1))))))
      (traverse 0 array-total-size-limit 0)
      (let ((end1 end))
        (setq max-depth 0)
        (traverse end1 array-total-size-limit 0)
        (values max-depth end1 end)))))

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

(defun second-max (list)
  (declare #.OPT
           (values uint32))
  (let ((max -1)
        (max2 -1))
    (declare (int32 max max2))
    (dolist (v list)
      (declare (uint32 v))
      (cond ((>= v max)
             (setq max2 max
                   max v))
            ((>= v max2)
             (setq max2 v))))
    max2))

(defun main ()
  (declare (inline sort))
  (let* ((n (read))
         (k (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         edges
         (res #xffffffff))
    (declare (uint32 n k res))
    (dotimes (i (- n 1))
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (push a (aref graph b))
        (push b (aref graph a))
        (push (cons a b) edges)))
    (when (<= (find-diameter graph) k)
      (println 0)
      (return-from main))
    (let ((k/2 (floor k 2))
          (dists (make-array n :element-type 'uint32)))
      (declare (uint32 k/2))
      (labels ((fill-dists! (v parent depth)
                 (declare (int32 v parent depth))
                 (setf (aref dists v) depth)
                 (dolist (child (aref graph v))
                   (declare (uint32 child))
                   (unless (= child parent)
                     (fill-dists! child v (+ depth 1)))))
               (get-max-depth (v parent)
                 (let ((res (aref dists v)))
                   (declare (uint32 res))
                   (dolist (child (aref graph v))
                     (declare (uint32 child))
                     (unless (= child parent)
                       (maxf res (get-max-depth child v))))
                   res)))
        (if (evenp k)
            (dotimes (root n)
              (when (cdr (aref graph root)) ;; exclude one branch case
                (fill dists +inf+)
                (fill-dists! root -1 0)
                (let ((branch-depths (loop for child in (aref graph root)
                                           collect (get-max-depth child root))))
                  (when (>= (second-max branch-depths) k/2)
                    (minf res (count-if (lambda (x) (> (the uint32 x) k/2)) dists))))))
            (loop
              for (root1 . root2) in edges
              when (and (car (aref graph root1))
                        (car (aref graph root2)))
              do (fill dists +inf+)
                 (fill-dists! root1 root2 0)
                 (fill-dists! root2 root1 0)
                 (let ((branch-depths1 (loop for child in (aref graph root1)
                                             collect (get-max-depth child root1)))
                       (branch-depths2 (loop for child in (aref graph root2)
                                             collect (get-max-depth child root2))))
                   (when (and (>= (reduce #'max branch-depths1) k/2)
                              (>= (reduce #'max branch-depths2) k/2))
                     (minf res (count-if (lambda (x) (> (the uint32 x) k/2)) dists))))))
        (println res)))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
1 3 1 2
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5
100 1 2 3 14 15 58 58 58 29
"
    "135
")))


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

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

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

;;;
;;; Diameter of tree
;;;

(defun find-diameter (graph)
  "Finds a diameter of a tree. Returns three values: the length of the diameter
and its two ends."
  (declare ((array list (*)) graph))
  (let ((end 0)
        (max-depth 0))
    (assert (> (length graph) 0))
    (labels ((traverse (v parent depth)
               (declare ((integer 0 #.array-total-size-limit) v parent depth))
               (when (> depth max-depth)
                 (setq max-depth depth
                       end v))
               (dolist (child (aref graph v))
                 (declare ((integer 0 #.most-positive-fixnum) child))
                 (unless (= child parent)
                   (traverse child v (+ depth 1))))))
      (traverse 0 array-total-size-limit 0)
      (let ((end1 end))
        (setq max-depth 0)
        (traverse end1 array-total-size-limit 0)
        (values max-depth end1 end)))))

(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))
         (k (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         edges
         (res #xffffffff))
    (declare (uint32 n k res))
    (dotimes (i (- n 1))
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (push a (aref graph b))
        (push b (aref graph a))
        (push (cons a b) edges)))
    (when (<= (find-diameter graph) k)
      (println 0)
      (return-from main))
    (let ((k/2 (floor k 2))
          (dists (make-array n :element-type 'uint32)))
      (declare (uint32 k/2))
      (labels ((fill-dists! (v parent depth)
                 (declare (int32 v parent depth))
                 (setf (aref dists v) depth)
                 (dolist (child (aref graph v))
                   (declare (uint32 child))
                   (unless (= child parent)
                     (fill-dists! child v (+ depth 1)))))
               (get-max-depth (v parent)
                 (let ((res (aref dists v)))
                   (declare (uint32 res))
                   (dolist (child (aref graph v))
                     (declare (uint32 child))
                     (unless (= child parent)
                       (maxf res (get-max-depth child v))))
                   res)))
        (if (evenp k)
            (dotimes (root n)
              (when (cdr (aref graph root)) ;; exclude one branch case
                (fill dists +inf+)
                (fill-dists! root -1 0)
                (let ((branch-depths (loop for child in (aref graph root)
                                           collect (get-max-depth child root))))
                  (setq branch-depths (sort branch-depths
                                            (lambda (x y)
                                              (declare (uint32 x y))
                                              (> x y))))
                  (when (>= (second branch-depths) k/2)
                    (minf res (count-if (lambda (x) (> (the uint32 x) k/2)) dists))))))
            (loop
              for (root1 . root2) in edges
              when (and (car (aref graph root1))
                        (car (aref graph root2)))
              do (fill dists +inf+)
                 (fill-dists! root1 root2 0)
                 (fill-dists! root2 root1 0)
                 (let ((branch-depths1 (loop for child in (aref graph root1)
                                             collect (get-max-depth child root1)))
                       (branch-depths2 (loop for child in (aref graph root2)
                                             collect (get-max-depth child root2))))
                   (when (and (>= (reduce #'max branch-depths1) k/2)
                              (>= (reduce #'max branch-depths2) k/2))
                     (minf res (count-if (lambda (x) (> (the uint32 x) k/2)) dists))))))
        (println res)))))

#-swank (main)

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

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

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

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
1 3 1 2
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5
100 1 2 3 14 15 58 58 58 29
"
    "135
")))