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

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

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

;;;
;;; Binomial coefficient with mod
;;; build: O(n)
;;; query: O(1)
;;;

(defconstant +binom-size+ 110000)
(defconstant +binom-mod+ #.(+ (expt 10 9) 7))

(declaim ((simple-array (unsigned-byte 32) (*)) *fact* *fact-inv* *inv*))
(defparameter *fact* (make-array +binom-size+ :element-type '(unsigned-byte 32)))
(defparameter *fact-inv* (make-array +binom-size+ :element-type '(unsigned-byte 32)))
(defparameter *inv* (make-array +binom-size+ :element-type '(unsigned-byte 32)))

(defun initialize-binom ()
  (setf (aref *fact* 0) 1
        (aref *fact* 1) 1
        (aref *fact-inv* 0) 1
        (aref *fact-inv* 1) 1
        (aref *inv* 1) 1)
  (loop for i from 2 below +binom-size+
        do (setf (aref *fact* i) (mod (* i (aref *fact* (- i 1))) +binom-mod+)
                 (aref *inv* i) (mod (- (* (aref *inv* (rem +binom-mod+ i))
                                           (floor +binom-mod+ i)))
                                     +binom-mod+)
                 (aref *fact-inv* i) (mod (* (aref *inv* i)
                                             (aref *fact-inv* (- i 1)))
                                          +binom-mod+))))

(initialize-binom)

(declaim (inline binom))
(defun binom (n k)
  "Returns nCk."
  (if (or (< n k) (< n 0) (< k 0))
      0
      (mod (* (aref *fact* n)
              (mod (* (aref *fact-inv* k) (aref *fact-inv* (- n k))) +binom-mod+))
           +binom-mod+)))

(defun multinomial (&rest ks)
  "Returns the multinomial coefficient K!/k_1!k_2!...k_n! for K = k_1 + k_2 +
... + k_n. K must be equal or smaller than MOST-POSITIVE-FIXNUM. (multinomial)
returns 1."
  (let ((sum 0)
        (result 1))
    (declare ((integer 0 #.most-positive-fixnum) result sum))
    (dolist (k ks)
      (incf sum k)
      (setq result
            (mod (* result (aref *fact-inv* k)) +binom-mod+)))
    (mod (* result (aref *fact* sum)) +binom-mod+)))

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (mem (make-array (+ n 1) :element-type 'int32 :initial-element -1))
         (l 0)
         (r 0))
    (declare (uint32 n))
    (dotimes (i (+ n 1))
      (let ((a (read-fixnum)))
        (if (= -1 (aref mem a))
            (setf (aref mem a) i)
            (setf l (aref mem a)
                  r i))))
    (with-output-buffer
      (loop for k from 1 to (+ n 1)
            do (println (mod (- (binom (+ n 1) k)
                                (binom (+ l (- n r)) (- k 1)))
                             +mod+))))))

#-swank(main)

Score : 600 points

Problem Statement

You are given an integer sequence of length n+1, a_1,a_2,...,a_{n+1}, which consists of the n integers 1,...,n.
It is known that each of the n integers 1,...,n appears at least once in this sequence.

For each integer k=1,...,n+1, find the number of the different subsequences (not necessarily contiguous) of the given sequence with length k, modulo 10^9+7.

Notes

If the contents of two subsequences are the same, they are not separately counted even if they originate from different positions in the original sequence.

A subsequence of a sequence a with length k is a sequence obtained by selecting k of the elements of a and arranging them without changing their relative order. For example, the sequences 1,3,5 and 1,2,3 are subsequences of 1,2,3,4,5, while 3,1,2 and 1,10,100 are not.

Constraints

1 \leq n \leq 10^5

1 \leq a_i \leq n

Each of the integers 1,...,n appears in the sequence.

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_{n+1}

Output

Print n+1 lines.
The k-th line should contain the number of the different subsequences of the given sequence with length k, modulo 10^9+7.

Sample Input 1

3
1 2 1 3

Sample Output 1

3
5
4
1

There are three subsequences with length 1: 1 and 2 and 3.

There are five subsequences with length 2: 1,1 and 1,2 and 1,3 and 2,1 and 2,3.

There are four subsequences with length 3: 1,1,3 and 1,2,1 and 1,2,3 and 2,1,3.

There is one subsequence with length 4: 1,2,1,3.

Sample Input 2

1
1 1

Sample Output 2

1
1

There is one subsequence with length 1: 1.

There is one subsequence with length 2: 1,1.

Sample Input 3

32
29 19 7 10 26 32 27 4 11 20 2 8 16 23 5 14 6 12 17 22 18 30 28 24 15 1 25 3 13 21 19 31 9

Sample Output 3

32
525
5453
40919
237336
1107568
4272048
13884156
38567100
92561040
193536720
354817320
573166440
818809200
37158313
166803103
166803103
37158313
818809200
573166440
354817320
193536720
92561040
38567100
13884156
4272048
1107568
237336
40920
5456
528
33
1

Be sure to print the numbers modulo 10^9+7.


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

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

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

;;;
;;; Binomial coefficient with mod
;;; build: O(n)
;;; query: O(1)
;;;

(defconstant +binom-size+ 110000)
(defconstant +binom-mod+ #.(+ (expt 10 9) 7))

(declaim ((simple-array (unsigned-byte 32) (*)) *fact* *fact-inv* *inv*))
(defparameter *fact* (make-array +binom-size+ :element-type '(unsigned-byte 32)))
(defparameter *fact-inv* (make-array +binom-size+ :element-type '(unsigned-byte 32)))
(defparameter *inv* (make-array +binom-size+ :element-type '(unsigned-byte 32)))

(defun initialize-binom ()
  (setf (aref *fact* 0) 1
        (aref *fact* 1) 1
        (aref *fact-inv* 0) 1
        (aref *fact-inv* 1) 1
        (aref *inv* 1) 1)
  (loop for i from 2 below +binom-size+
        do (setf (aref *fact* i) (mod (* i (aref *fact* (- i 1))) +binom-mod+)
                 (aref *inv* i) (mod (- (* (aref *inv* (rem +binom-mod+ i))
                                           (floor +binom-mod+ i)))
                                     +binom-mod+)
                 (aref *fact-inv* i) (mod (* (aref *inv* i)
                                             (aref *fact-inv* (- i 1)))
                                          +binom-mod+))))

(initialize-binom)

(declaim (inline binom))
(defun binom (n k)
  "Returns nCk."
  (if (or (< n k) (< n 0) (< k 0))
      0
      (mod (* (aref *fact* n)
              (mod (* (aref *fact-inv* k) (aref *fact-inv* (- n k))) +binom-mod+))
           +binom-mod+)))

(defun multinomial (&rest ks)
  "Returns the multinomial coefficient K!/k_1!k_2!...k_n! for K = k_1 + k_2 +
... + k_n. K must be equal or smaller than MOST-POSITIVE-FIXNUM. (multinomial)
returns 1."
  (let ((sum 0)
        (result 1))
    (declare ((integer 0 #.most-positive-fixnum) result sum))
    (dolist (k ks)
      (incf sum k)
      (setq result
            (mod (* result (aref *fact-inv* k)) +binom-mod+)))
    (mod (* result (aref *fact* sum)) +binom-mod+)))

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (mem (make-array (+ n 1) :element-type 'int32 :initial-element -1))
         (l 0)
         (r 0))
    (declare (uint32 n))
    (dotimes (i (+ n 1))
      (let ((a (read-fixnum)))
        (if (= -1 (aref mem a))
            (setf (aref mem a) i)
            (setf l (aref mem a)
                  r i))))
    (with-output-buffer
      (loop for k from 1 to (+ n 1)
            do (println (mod (+ (binom (- n 1) k)
                                (- (* 2 (binom (- n 1) (- k 1)))
                                   (binom (+ l (- n r)) (- k 1)))
                                (binom (- n 1) (- k 2)))
                             +mod+))))))

#-swank(main)

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

Submitted source-code file size, in bytes.

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

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


(let ((x (read))
    (a (read))
    (b (read))
    (ans "dangerous"))

    (if (<= 0 (- a b))
    (setq ans "delicious")
        (if (>= x (- b a))
        (setq ans "safe")))
    (princ ans)
)

Score : 100 points

Problem Statement

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier.
He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache.

Constraints

1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache.

Sample Input 1

4 3 6

Sample Output 1

safe

He ate the food three days after the "best-by" date. It was not delicious or harmful for him.

Sample Input 2

6 5 1

Sample Output 2

delicious

He ate the food by the "best-by" date. It was delicious for him.

Sample Input 3

3 7 12

Sample Output 3

dangerous

He ate the food five days after the "best-by" date. It was harmful for him.


(let* ((n (read))
       (vec (concatenate 'vector (loop repeat n
                                       collect (read)))))

  (defun f (v &optional (pos 0) (cnt 0))
    (if (> cnt n)
      -1
      (if (= pos 1)
        cnt
        (f v (1- (aref v pos)) (1+ cnt)))))

  (format t "~A~%"
          (f vec)))

Score : 200 points

Problem Statement

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up.
These buttons are numbered 1 through N.
When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It is possible that i=a_i.
When Button i is not lighten up, nothing will happen by pressing it.

Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

Print -1 if it is impossible to lighten up Button 2.
Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button 1, then Button 3.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

Pressing Button 1 lightens up Button 3, and vice versa, so Button 2 will never be lighten up.

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3


(declaim (optimize (sped 3) (debug 0) (safety 0)))

(defun fact (n)
  (loop for a = 1 then (mod (* a i) 1000000007)
        for i from 2 to n
        finally (return a)))

(format t "~A~%" (let ((n (read))
                       (m (read)))
                   (case (abs (- n m))
                     (1 (if (> n m)
                            (mod (* (expt (fact m) 2) n) 1000000007)
                            (mod (* (expt (fact n) 2) m) 1000000007)))
                     (0 (mod (* 2 (expt (fact n) 2)) 1000000007))
                     (t 0))))

Score : 300 points

Problem Statement

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477


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

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

(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (terminate-char #\Space))
  "Note that the returned string will be reused."
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let ((,buffer (load-time-value (make-string ,buffer-size
                                                  :element-type 'base-char))))
       (declare (simple-base-string ,buffer))
       (loop for ,character of-type base-char =
                #-swank (code-char (read-byte ,in nil #\Newline))
                #+swank (read-char ,in nil #\Newline)
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (setf (schar ,buffer ,idx) ,terminate-char)
                     (return (values ,buffer ,idx))))))

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

(defstruct (union-find
            (:constructor make-union-find
                (size &aux (parents (let ((seq (make-array size :element-type 'non-negative-fixnum)))
                                      (dotimes (i size seq) (setf (aref seq i) i))))
                           (ranks (make-array size :element-type 'non-negative-fixnum
                                                   :initial-element 0)))))
  (parents nil :type (simple-array non-negative-fixnum (*)))
  (ranks nil :type (simple-array non-negative-fixnum (*))))

(declaim (ftype (function * (values non-negative-fixnum &optional)) uf-root))
(defun uf-root (x uf-tree)
  "Returns the root of X."
  (declare (optimize (speed 3))
           (non-negative-fixnum x))
  (let ((parents (union-find-parents uf-tree)))
    (if (= x (aref parents x))
        x
        (setf (aref parents x)
              (uf-root (aref parents x) uf-tree)))))

(declaim (inline uf-unite!))
(defun uf-unite! (x1 x2 uf-tree)
  "Unites X1 and X2 destructively."
  (let ((root1 (uf-root x1 uf-tree))
        (root2 (uf-root x2 uf-tree))
        (parents (union-find-parents uf-tree))
        (ranks (union-find-ranks uf-tree)))
    (cond ((= root1 root2) nil)
          ((< (aref ranks root1) (aref ranks root2))
           (setf (aref parents root1) root2))
          ((= (aref ranks root1) (aref ranks root2))
           (setf (aref parents root2) root1)
           (incf (aref ranks root1)))
          (t (setf (aref parents root2) root1)))))

(declaim (inline uf-connected-p))
(defun uf-connected-p (x1 x2 uf-tree)
  "Checks if X1 and X2 have the same root."
  (= (uf-root x1 uf-tree) (uf-root x2 uf-tree)))

;; (defun bench ()
;;   (let* ((size 5000000)
;;          (tree (make-union-find size))
;;          (seed (seed-random-state 0)))
;;     (dotimes (i 5000000)
;;       (uf-unite! (random size seed) (random size seed) tree))))

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

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

;; Hauptteil

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         ;; (x y idx)
         (table (make-array n :element-type '(cons uint32 (cons uint32 uint32)))))
    (dotimes (i n)
      (split-ints-and-bind (x y) (buffered-read-line)
        (setf (aref table i) (list x y i))))
    (let ((table-x (stable-sort (copy-seq table) #'< :key #'first))
          (table-y (stable-sort table #'< :key #'second))
          ;; (cost from to)
          (edges (make-array (* 2 (- n 1)) :element-type '(cons uint32 (cons uint32 uint32)))))
      (loop for j of-type uint32 below (- n 1)
            do (destructuring-bind (x1 y1 city1) (aref table-x j)
                 (destructuring-bind (x2 y2 city2) (aref table-x (+ j 1))
                   (declare (uint32 x1 y1 x2 y2 city1 city2))
                   (setf (aref edges (+ j j))
                         (list (min (abs (- x2 x1)) (abs (- y2 y1))) city1 city2))))
               (destructuring-bind (x1 y1 city1) (aref table-y j)
                 (destructuring-bind (x2 y2 city2) (aref table-y (+ j 1))
                   (declare (uint32 x1 y1 x2 y2 city1 city2))
                   (setf (aref edges (+ j j 1))
                         (list (min (abs (- x2 x1)) (abs (- y2 y1))) city1 city2))))
            finally (setf edges (stable-sort edges #'< :key #'first)))
      (let ((tree (make-union-find n))
            (cost-sum 0))
        (dotimes (i (length edges))
          (destructuring-bind (cost from to) (aref edges i)
            (unless (uf-connected-p from to tree)
              (uf-unite! from to tree)
              (incf cost-sum cost))))
        (println cost-sum)))))

#-swank(main)

Score : 500 points

Problem Statement

There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

2 ≤ N ≤ 10^5

0 ≤ x_i,y_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.

Sample Input 1

3
1 5
3 9
7 8

Sample Output 1

3

Build a road between Towns 1 and 2, and another between Towns 2 and 3. The total cost is 2+1=3 yen.

Sample Input 2

6
8 3
4 9
12 19
18 1
13 5
7 6

Sample Output 2

8


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

;; BEGIN_INSERTED_CONTENTS
(declaim (ftype (function * (values fixnum &optional)) read-fixnum))
(defun read-fixnum (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (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))))))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT
           (inline sort))
  (let* ((r (read))
         (c (read))
         (n (read))
         queries)
    (declare (uint31 r c n))
    (labels ((on-edge-p (y x)
               (or (zerop y) (zerop x)
                   (= y r) (= x c)))
             (render (y x)
               (cond ((zerop y) x)
                     ((= x c) (+ c y))
                     ((= y r) (+ c r (- c x)))
                     (t (+ c r c (- r y))))))
      (dotimes (i n)
        (let ((y1 (read-fixnum))
              (x1 (read-fixnum))
              (y2 (read-fixnum))
              (x2 (read-fixnum)))
          (declare (uint31 y1 x1 y2 x2))
          (when (and (on-edge-p y1 x1)
                     (on-edge-p y2 x2))
            (let ((pos1 (render y1 x1))
                  (pos2 (render y2 x2)))
              (when (> pos1 pos2) (rotatef pos1 pos2))
              (push (list* pos1 i :add) queries)
              (push (list* pos2 i :delete) queries)))))
      (setq queries (sort queries #'< :key (lambda (x) (the fixnum (car x))))))
    (let (stack)
      (loop for (_ idx . op) in queries
            do (cond ((eq op :add)
                      (push idx stack))
                     ((= (car stack) idx)
                      (pop stack))
                     (t
                      (write-line "NO")
                      (return-from main))))
      (write-line "YES"))))

#-swank (main)

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

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

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

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

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

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

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

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

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

Score : 700 points

Problem Statement

Snuke is playing a puzzle game.
In this game, you are given a rectangular board of dimensions R × C, filled with numbers. Each integer i from 1 through N is written twice, at the coordinates (x_{i,1},y_{i,1}) and (x_{i,2},y_{i,2}).

The objective is to draw a curve connecting the pair of points where the same integer is written, for every integer from 1 through N.
Here, the curves may not go outside the board or cross each other.

Determine whether this is possible.

Constraints

1 ≤ R,C ≤ 10^8

1 ≤ N ≤ 10^5

0 ≤ x_{i,1},x_{i,2} ≤ R(1 ≤ i ≤ N)

0 ≤ y_{i,1},y_{i,2} ≤ C(1 ≤ i ≤ N)

All given points are distinct.

All input values are integers.

Input

Input is given from Standard Input in the following format:

R C N
x_{1,1} y_{1,1} x_{1,2} y_{1,2}
:
x_{N,1} y_{N,1} x_{N,2} y_{N,2}

Output

Print YES if the objective is achievable; print NO otherwise.

Sample Input 1

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

Sample Output 1

YES

The above figure shows a possible solution.

Sample Input 2

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

Sample Output 2

NO

Sample Input 3

5 5 7
0 0 2 4
2 3 4 5
3 5 5 2
5 5 5 4
0 3 5 1
2 2 4 4
0 5 4 1

Sample Output 3

YES

Sample Input 4

1 1 2
0 0 1 1
1 0 0 1

Sample Output 4

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

(defun main ()
  (let* ((s (read-line))
         (n (length s)))
    (labels ((calc-cost (c)
               (let ((res 0)
                     (prev 0))
                 (loop
                   (let ((next (or (position c s :start prev) n)))
                     (maxf res (- next prev))
                     (when (= next n)
                       (return res))
                     (setq prev (+ next 1)))))))
      (println
       (loop for c across "abcdefghijklmnopqrstuvwxyz"
             minimize (calc-cost c))))))

#-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 "serval
"
    "3
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "jackal
"
    "2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "zzz
"
    "0
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "whbrjpjyhsrywlqjxdbrbaomnw
"
    "8
")))

Score : 300 points

Problem Statement

Snuke can change a string t of length N into a string t' of length N - 1 under the following rule:

For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.

There is a string s consisting of lowercase English letters.
Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same.
Find the minimum necessary number of operations.

Constraints

1 ≤ |s| ≤ 100

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

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

Sample Input 1

serval

Sample Output 1

3

One solution is: serval → srvvl → svvv → vvv.

Sample Input 2

jackal

Sample Output 2

2

One solution is: jackal → aacaa → aaaa.

Sample Input 3

zzz

Sample Output 3

0

All the characters in s are the same from the beginning.

Sample Input 4

whbrjpjyhsrywlqjxdbrbaomnw

Sample Output 4

8

In 8 operations, he can change s to rrrrrrrrrrrrrrrrrr.


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

(let* ((n (read)) (l (loop for i from 1 to n collect (read))))
  (princ (- (reduce #'max l) (reduce #'min l))))

Score : 200 points

Problem Statement

It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.

There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.

Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.

Constraints

1 ≤ N ≤ 100

0 ≤ a_i ≤ 1000

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum distance to be traveled.

Sample Input 1

4
2 3 7 9

Sample Output 1

7

The travel distance of 7 can be achieved by starting at coordinate 9 and traveling straight to coordinate 2.

It is not possible to do with a travel distance of less than 7, and thus 7 is the minimum distance to be traveled.

Sample Input 2

8
3 1 4 1 5 9 2 6

Sample Output 2

8

There may be more than one house at a position.


(defun solver (&aux (max 0) (min 1001) temp)
  (let ((n (read)))
    (loop repeat n do
          (setf temp (read))
          (when (> temp max) (setf max temp))
          (when (< temp min) (setf min temp)))
    (format t "~A~%" (- max min))))

(solver)


(let ((n (read))
    (other 0)
    (ans 0))
    (defparameter *hash* (make-hash-table))

    (loop for i below n do
        (case (floor (/ (read) 400))
            (0 (setf (gethash 'hai *hash*) 1))
            (1 (setf (gethash 'cha *hash*) 1))
            (2 (setf (gethash 'midori *hash*) 1))
            (3 (setf (gethash 'mizu *hash*) 1))
            (4 (setf (gethash 'ao *hash*) 1))
            (5 (setf (gethash 'ki *hash*) 1))
            (6 (setf (gethash 'daidai *hash*) 1))
            (7 (setf (gethash 'aka *hash*) 1))
            ((8 9 10 11 12) (incf other))
        )
    )
    (maphash #'(lambda (key value)
            (if (= value 1)
                (incf ans)
            )
        )
    *hash*)

    (if (= ans 0)
        (format t "1")
        (format t "~D" ans)
    )

    (incf ans other)
    (if (<= 8 ans)
        (format t " 8~%")
        (format t " ~D~%" ans)
    )
)

Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


(defun collector (function lst); listの各要素を数えるコレクタ 10^7くらいまで
  (if lst
      (let* ((ans '())
             (mem (cons (car lst) 1)))
        (mapcar (lambda (k)
                  (if (funcall function k (car mem))
                      (incf (cdr mem))
                      (progn (push mem ans)
                             (setf mem (cons k 1))))) (cdr lst))
        (push mem ans)
        ans)
      '()))

(let* ((n (read))
       (lst (sort (loop :repeat n :collect (read)) #'<))
       (over3200 0)
       (ln (count-if (lambda (x) (<= 0 x))
                     (collector #'= (mapcar (lambda (x) (if (<= 3200 x)
                                                            (progn (incf over3200) -1)
                                                            (floor x 400))) lst)) :key #'car)))
  (if (and (= ln 0) (not (= over3200 0)))
      (format t "1 1")
      (format t "~A ~A" ln (if (<= (+ ln over3200) 8)
                               (+ ln over3200)
                               8))))


(defun collector (function lst); listの各要素を数えるコレクタ 10^7くらいまで
  (if lst
      (let* ((ans '())
             (mem (cons (car lst) 1)))
        (mapcar (lambda (k)
                  (if (funcall function k (car mem))
                      (incf (cdr mem))
                      (progn (push mem ans)
                             (setf mem (cons k 1))))) (cdr lst))
        (push mem ans)
        ans)
      '()))

(let* ((n (read))
       (lst (sort (loop :repeat n :collect (read)) #'<))
       (over3200 0)
       (ln (count-if (lambda (x) (<= 0 x))
                     (collector #'= (mapcar (lambda (x) (if (<= 3200 x)
                                                            (progn (incf over3200) -1)
                                                            (floor x 400))) lst)) :key #'car)))
  (format t "~A ~A" ln (+ ln over3200)))


(let* ((a (read))
       (li (loop :repeat a collect (read)))
       (hi 0))
  (map-into li (lambda (n)
            (case (floor n 400)
              (1 1)
              (2 2)
              (3 3)
              (4 4)
              (5 5)
              (6 6)
              (7 7)
              (otherwise (setq hi (1+ hi))))) li)
  (setf li (remove-duplicates li))
  (format t "~A ~A" (if (< (length li) hi)
                        hi (length li)) (+ (length li) hi)))


(defvar +rate+
  '((399 . "gray")
    (799 . "brown")
    (1199 . "green")
    (1599 . "cyan")
    (1999 . "blue")
    (2399 . "yellow")
    (2799 . "orange")
    (3199 . "red")))

(defun select-color (point)
  (loop for (rate . color) in +rate+
        when (<= point rate)
        return color))

(let ((n (read))
      (a (make-hash-table))
      (any 0))
  (dotimes (i n)
    (let ((color (select-color (read))))
      (if color
          (setf (gethash color a)
                (1+ (gethash color a 0)))
          (incf any))))
  (let* ((count (loop for key being each hash-key of a
                      using (hash-value value)
                      count (< 0 value)))
         (mini (max count))
         (maxi (min (+ count any) 8)))
    (format t "~A ~A~%" mini maxi)))


Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


(setq s(read-line))
(setq f 0)
(loop for i from 0 to (1-(length s))do
	  (loop for j from (1+ i)to(1-(length s))do
			(if(char=(char s i)(char s j))(incf f))))
(princ(if(> f 0)"no""yes"))

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.

Constraints

2 ≤ |S| ≤ 26, where |S| denotes the length of S.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If all the characters in S are different, print yes (case-sensitive); otherwise, print no.

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes


(defun sum (list)
  (reduce #'+ list :initial-value 0))

(defun search-min (list)
  (let ((result (car list)))
    (dolist (i list)
      (if (and (< i result) (not (= 0 (mod i 10))))
          (setf result i)))
    (if (= 0 (mod result 10))
        (sum list)
        result)))

(defun main ()
  (let ((times (read))
        (list nil))
    (dotimes (i times)
      (setf list (cons (read) list)))
    (format t "~A~%" (- (sum list) (search-min list)))))

(main)

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.


(let* ((n (read))
    (s (make-array n))
    (ans 0)
    (herasu 0))
    (loop for i below n do
        (progn
            (setf (aref s i) (read))
            (incf ans (aref s i))
        )
    )
    (setf s (sort s #'<))
    (loop for i below n do
        (if (not (zerop (rem (aref s i) 10)))
            (progn
                (setf herasu (aref s i))
                (return)
            )
        )
    )
    (if (zerop (rem ans 10))
        (if (zerop herasu)
            (setq ans 0)
            (decf ans herasu)
        )
    )
    (format t "~D~%" ans)
)


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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (a (read))
         (b (read))
         (delta (- a b))
         (hs (make-array 100000 :element-type 'uint32))
         (tmp-hs (make-array 100000 :element-type 'uint32)))
    (declare (uint31 delta a b n))
    (dotimes (i n) (setf (aref hs i) (read-fixnum)))
    (labels ((feasible-p (k)
               (declare (uint31 k))
               (let ((base (* k b)))
                 (dotimes (i n) (setf (aref tmp-hs i) (max 0 (- (aref hs i) base))))
                 (<= (loop for h across tmp-hs
                           sum (ceiling h delta) of-type fixnum)
                     k))))
      (let ((sup (ceiling (reduce #'max hs) b)))
        (nlet bisect ((ng 0) (ok sup))
          (declare (uint31 ng ok))
          (if (<= (- ok ng) 1)
              (println ok)
              (let ((mid (ash (+ ok ng) -1)))
                (if (feasible-p mid)
                    (bisect ng mid)
                    (bisect mid ok)))))))))

#-swank(main)

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.

Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows:

Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by A, and the health of each of the other monsters will decrease by B. Here, A and B are predetermined parameters, and A > B holds.

At least how many explosions do you need to cause in order to vanish all the monsters?

Constraints

All input values are integers.

1 ≤ N ≤ 10^5

1 ≤ B < A ≤ 10^9

1 ≤ h_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N A B
h_1
h_2
:
h_N

Output

Print the minimum number of explosions that needs to be caused in order to vanish all the monsters.

Sample Input 1

4 5 3
8
7
4
2

Sample Output 1

2

You can vanish all the monsters in two explosion, as follows:

First, cause an explosion centered at the monster with 8 health. The healths of the four monsters become 3, 4, 1 and -1, respectively, and the last monster vanishes.

Second, cause an explosion centered at the monster with 4 health remaining. The healths of the three remaining monsters become 0, -1 and -2, respectively, and all the monsters are now vanished.

Sample Input 2

2 10 4
20
20

Sample Output 2

4

You need to cause two explosions centered at each monster, for a total of four.

Sample Input 3

5 2 1
900000000
900000000
1000000000
1000000000
1000000000

Sample Output 3

800000000


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

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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (a (read))
         (b (read))
         (delta (- a b))
         (hs (make-array n :element-type 'uint32)))
    (declare (uint31 delta a b))
    (dotimes (i n) (setf (aref hs i) (read-fixnum)))
    (labels ((feasible-p (k)
               (declare (uint31 k))
               (let ((hs (copy-seq hs))
                     (base (* k b)))
                 (dotimes (i n) (setf (aref hs i) (max 0 (- (aref hs i) base))))
                 (<= (the uint32
                          (reduce #'+ hs
                                  :key (lambda (h) (ceiling (the uint31 h) delta))))
                     k))))
      (let ((sup (ceiling (reduce #'max hs) b)))
        (nlet bisect ((ng 0) (ok sup))
          (declare (uint31 ng ok))
          (if (<= (- ok ng) 1)
              (println ok)
              (let ((mid (ash (+ ok ng) -1)))
                (if (feasible-p mid)
                    (bisect ng mid)
                    (bisect mid ok)))))))))

#-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 (progn (ql:quickload '(:cl-debug-print :fiveam))
                 (shadow :run)
                 (use-package :fiveam)))
#+swank (cl-syntax:use-syntax cl-debug-print:debug-print-syntax)

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Calculates inversion number by merge sort
;;;

;; Introduce INIT-VECTOR for better type-propagation on SBCL
#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-c:defknown init-vector (vector)
      vector (sb-c:flushable)
    :overwrite-fndb-silently t)

  (sb-c:defoptimizer (init-vector sb-c:derive-type) ((template))
    (let* ((template-type (sb-c::lvar-type template))
           (spec `(,(if (sb-kernel:array-type-complexp template-type) 'array 'simple-array)
                   ,(sb-kernel:type-specifier (sb-kernel:array-type-element-type template-type))
                   (*))))
      (sb-c::careful-specifier-type spec))))

(defun init-vector (template)
  "Returns a newly initialized vector of the same type as TEMPLATE vector with
SIZE."
  (declare (optimize (speed 3)))
  (make-array (length template) :element-type (array-element-type template)))

(declaim (inline %merge-count))
(defun %merge-count (l mid r source-vec dest-vec predicate)
  (declare ((mod #.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-bubble-sort!))
(defun %calc-by-bubble-sort! (vec predicate l r)
  (declare (function predicate)
           ((mod #.array-total-size-limit) l r))
  (loop for end from r above l
        sum (loop with inv-count of-type (integer 0 #.most-positive-fixnum) = 0
                  for i from l below (- end 1)
                  do (when (funcall predicate (aref vec (+ i 1)) (aref vec i))
                       (rotatef (aref vec i) (aref vec (+ i 1)))
                       (incf inv-count))
                  finally (return inv-count))
        of-type (integer 0 #.most-positive-fixnum)))

(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 ((mod #.array-total-size-limit) start end))
    (assert (<= start end))
    (let ((buffer (init-vector vector)))
      (symbol-macrolet ((vec1 vector) (vec2 buffer))
        (labels ((recurse (l r merge-to-vec1-p)
                   (declare (optimize (safety 0))
                            ((mod #.array-total-size-limit) l r))
                   (cond ((= l r) 0)
                         ((and merge-to-vec1-p (<= (- r l) 8))
                          (%calc-by-bubble-sort! vec1 predicate l r))
                         (t
                          (let ((mid (ash (+ l r) -1)))
                            (with-fixnum+
                                (+ (recurse l mid (not merge-to-vec1-p))
                                   (recurse mid r (not merge-to-vec1-p))
                                   (if merge-to-vec1-p
                                       (%merge-count l mid r vec2 vec1 predicate)
                                       (%merge-count l mid r vec1 vec2 predicate)))))))))
          (recurse start end t))))))

(defmacro %bench-sort (sort-func predicate size count &optional (sample 1))
  (let ((state (gensym))
        (vector (gensym))
        (idx (gensym)))
    `(let* ((,state (sb-ext:seed-random-state 0))
            (,vector (make-array ,size :element-type 'fixnum)))
       (declare (optimize (speed 3))
                ((simple-array fixnum (,size)) ,vector))
       (,@(if (= sample 1)
              `(galante:time-after-gc)
              `(galante:time-median ,sample))
         (loop repeat ,count
               do (dotimes (,idx ,size)
                    (setf (aref ,vector ,idx) (random #xffffffff ,state)))
               sum (funcall ,sort-func ,vector ,predicate)
               of-type fixnum)))))

(defun bench-sort ()
  (%bench-sort #'calc-inversion-number! #'< 1000000 20))

(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
                                  ;; (return-from read-fixnum 0)
                                  (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) (the fixnum (* result 10))))
              (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)

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (k (read))
         (as (make-array n :element-type 'int32))
         (cumul (make-array (1+ n) :element-type 'fixnum :initial-element 0)))
    (declare (uint31 n k))
    (dotimes (i n)
      (setf (aref as i) (- (read-fixnum) k))
      (setf (aref cumul (1+ i)) (+ (aref cumul i) (aref as i))))
    (println (- (floor (* n (+ n 1)) 2)
                (calc-inversion-number! cumul #'<)))))

#-swank(main)

Score : 600 points

Problem Statement

You are given an integer sequence of length N, a = {a_1, a_2, …, a_N}, and an integer K.

a has N(N+1)/2 non-empty contiguous subsequences, {a_l, a_{l+1}, …, a_r} (1 ≤ l ≤ r ≤ N). Among them, how many have an arithmetic mean that is greater than or equal to K?

Constraints

All input values are integers.

1 ≤ N ≤ 2 \times 10^5

1 ≤ K ≤ 10^9

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N K
a_1
a_2
:
a_N

Output

Print the number of the non-empty contiguous subsequences with an arithmetic mean that is greater than or equal to K.

Sample Input 1

3 6
7
5
7

Sample Output 1

5

All the non-empty contiguous subsequences of a are listed below:

{a_1} = {7}

{a_1, a_2} = {7, 5}

{a_1, a_2, a_3} = {7, 5, 7}

{a_2} = {5}

{a_2, a_3} = {5, 7}

{a_3} = {7}

Their means are 7, 6, 19/3, 5, 6 and 7, respectively, and five among them are 6 or greater. Note that {a_1} and {a_3} are indistinguishable by the values of their elements, but we count them individually.

Sample Input 2

1 2
1

Sample Output 2

0

Sample Input 3

7 26
10
20
30
40
30
20
10

Sample Output 3

13


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

;; BEGIN_INSERTED_CONTENTS
(declaim (inline get-2dcumul))
(defun get-2dcumul (cumul-table i0 j0 i1 j1)
  "Returns the cumulative sum of the region given by the rectangle [i0, i1)*[j0,
j1). CUMUL-TABLE must be appropriately initialized beforehand:
i.e. CUMUL-TABLE[i][j] = sum of the region given by the regtangle [0, i)*[0,
j)."
  (+ (- (aref cumul-table i1 j1)
        (aref cumul-table i0 j1)
        (aref cumul-table i1 j0))
     (aref cumul-table i0 j0)))

(declaim (inline initialize-2dcumul))
(defun initialize-2dcumul (cumul-table)
  (destructuring-bind (h+1 w+1) (array-dimensions cumul-table)
    (declare ((integer 0 #.most-positive-fixnum) h+1 w+1))
    (let ((h (- h+1 1))
          (w (- w+1 1)))
      (declare ((integer 0 #.most-positive-fixnum) h w))
      (dotimes (i h+1)
        (dotimes (j w)
          (incf (aref cumul-table i (+ j 1))
                (aref cumul-table i j))))
      (dotimes (j w+1)
        (dotimes (i h)
          (incf (aref cumul-table (+ i 1) j)
                (aref cumul-table i j)))))))

(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 (inline read-schar))
(defun read-schar (&optional (stream *standard-input*))
  (declare #-swank (sb-kernel:ansi-stream stream)
           (inline read-byte))
  #+swank (read-char stream nil #\Newline) ; on SLIME
  #-swank (code-char (read-byte stream nil #.(char-code #\Newline))))

(in-package :cl-user)

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (m (read))
         (q (read))
         (plan (make-array (list n m) :element-type 'bit :initial-element 0))
         (dp (make-array (list (+ n 1) (+ m 1)) :element-type 'uint31 :initial-element 0))
         (dp-h (make-array (list (+ n 1) (+ m 1)) :element-type 'uint31 :initial-element 0))
         (dp-v (make-array (list (+ n 1) (+ m 1)) :element-type 'uint31 :initial-element 0)))
    (declare (uint31 n m q))
    (dotimes (i n)
      (dotimes (j m (read-schar))
        (when (char= #\1 (read-schar))
          (setf (aref plan i j) 1))))
    (dotimes (i n)
      (dotimes (j m)
        (when (= 1 (aref plan i j))
          (incf (aref dp (+ i 1) (+ j 1)))
          (when (and (> j 0) (= 1 (aref plan i (- j 1))))
            (incf (aref dp-h (+ i 1) (+ j 1))))
          (when (and (> i 0) (= 1 (aref plan (- i 1) j)))
            (incf (aref dp-v (+ i 1) (+ j 1)))))))
    (initialize-2dcumul dp)
    (initialize-2dcumul dp-h)
    (initialize-2dcumul dp-v)
    (write-string
     (with-output-to-string (*standard-output* nil :element-type 'base-char)
       (dotimes (i q)
         (let ((y1 (- (read-fixnum) 1))
               (x1 (- (read-fixnum) 1))
               (y2 (read-fixnum))
               (x2 (read-fixnum)))
           (println (- (get-2dcumul dp y1 x1 y2 x2)
                       (get-2dcumul dp-h y1 (+ x1 1) y2 x2)
                       (get-2dcumul dp-v (+ y1 1) x1 y2 x2)))))))))

#-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 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4
"
    "3
2
2
2
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "5 5 6
11010
01110
10101
11101
01010
1 1 5 5
1 2 4 5
2 3 3 4
3 3 3 3
3 1 3 5
1 1 3 4
"
    "3
2
1
1
3
2
")))

Score : 700 points

Problem Statement

Nuske has a grid with N rows and M columns of squares. The rows are numbered 1 through N from top to bottom, and the columns are numbered 1 through M from left to right.
Each square in the grid is painted in either blue or white. If S_{i,j} is 1, the square at the i-th row and j-th column is blue; if S_{i,j} is 0, the square is white.
For every pair of two blue square a and b, there is at most one path that starts from a, repeatedly proceeds to an adjacent (side by side) blue square and finally reaches b, without traversing the same square more than once.

Phantom Thnook, Nuske's eternal rival, gives Q queries to Nuske. The i-th query consists of four integers x_{i,1}, y_{i,1}, x_{i,2} and y_{i,2} and asks him the following: when the rectangular region of the grid bounded by (and including) the x_{i,1}-th row, x_{i,2}-th row, y_{i,1}-th column and y_{i,2}-th column is cut out, how many connected components consisting of blue squares there are in the region?

Process all the queries.

Constraints

1 ≤ N,M ≤ 2000

1 ≤ Q ≤ 200000

S_{i,j} is either 0 or 1.

S_{i,j} satisfies the condition explained in the statement.

1 ≤ x_{i,1} ≤ x_{i,2} ≤ N(1 ≤ i ≤ Q)

1 ≤ y_{i,1} ≤ y_{i,2} ≤ M(1 ≤ i ≤ Q)

Input

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

N M Q
S_{1,1}..S_{1,M}
:
S_{N,1}..S_{N,M}
x_{1,1} y_{i,1} x_{i,2} y_{i,2}
:
x_{Q,1} y_{Q,1} x_{Q,2} y_{Q,2}

Output

For each query, print the number of the connected components consisting of blue squares in the region.

Sample Input 1

3 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4

Sample Output 1

3
2
2
2

In the first query, the whole grid is specified. There are three components consisting of blue squares, and thus 3 should be printed.

In the second query, the region within the red frame is specified. There are two components consisting of blue squares, and thus 2 should be printed.
Note that squares that belong to the same component in the original grid may belong to different components.

Sample Input 2

5 5 6
11010
01110
10101
11101
01010
1 1 5 5
1 2 4 5
2 3 3 4
3 3 3 3
3 1 3 5
1 1 3 4

Sample Output 2

3
2
1
1
3
2


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

(defun print-# (w)
  (dotimes (i (+ w 2))
	(princ #\#)))

(let ((h (read)) (w (read)))
  (print-# w)
  (fresh-line)
  (dotimes (i h)
	(princ #\#)
	(princ (read-line))
	(princ #\#)
	(fresh-line))
  (print-# w)
  (fresh-line))

Score : 200 points

Problem Statement

You are given a image with a height of H pixels and a width of W pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the i-th row from the top and j-th column from the left is a_{ij}.

Put a box around this image and output the result. The box should consist of # and have a thickness of 1.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

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

Output

Print the image surrounded by a box that consists of # and has a thickness of 1.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
		    vars
		    (mapcar (constantly '(read))
			    vars)))
       ,@body)))

(defsolver prob-c (h w)
  (cond ((and (= h 2)
	      (= w 2))
	 (format t "1"))
	((or (= (mod h 3) 0)
	     (= (mod w 3) 0))
	 (format t "0"))
	(t
	 (format t "~a" (+ h w)))))

(prob-c)

Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


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

;; BEGIN_INSERTED_CONTENTS
(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (terminate-char #\Space))
  "Note that the returned string will be reused."
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let ((,buffer (load-time-value (make-string ,buffer-size
                                                  :element-type 'base-char))))
       (declare (simple-base-string ,buffer))
       (loop for ,character of-type base-char =
                #-swank (code-char (read-byte ,in nil #.(char-code #\Newline)))
                #+swank (read-char ,in nil #\Newline)
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,terminate-char))
                     (return (values ,buffer ,idx))))))

;;;
;;; Ford-Fulkerson
;;;
(deftype edge () '(cons (unsigned-byte 62) t))

(declaim (inline %make-edge))
(defun %make-edge (to &key (capacity 0) reversed)
  (declare ((unsigned-byte 31) to capacity)
           (values edge))
  (cons (+ capacity (ash to 31))
        reversed))

(declaim (inline edge-reversed))
(defun edge-reversed (edge)
  (cdr edge))

(declaim (inline (setf edge-reversed)))
(defun (setf edge-reversed) (new-value edge)
  (setf (cdr edge) new-value))

(declaim (inline edge-capacity))
(defun edge-capacity (edge)
  (logand (car edge) #.(- (expt 2 31) 1)))

(declaim (inline (setf edge-capacity)))
(defun (setf edge-capacity) (new-value edge)
  (declare ((unsigned-byte 31) new-value))
  (setf (car edge)
        (logior new-value (logand (car edge) #.(ash (- (expt 2 31) 1) 31)))))

(declaim (inline edge-to))
(defun edge-to (edge)
  (ash (the (unsigned-byte 62) (car edge)) -31))

(defun push-edge (from-idx to-idx capacity graph &key bidirectional)
  "FROM-IDX, TO-IDX := index of vertex
GRAPH := vector of list of all the edges that goes from the vertex"
  (declare #.OPT
           ((simple-array list (*)) graph))
  (let* ((dep (%make-edge to-idx :capacity capacity))
         (ret (%make-edge from-idx
                          :capacity (if bidirectional capacity 0)
                          :reversed dep)))
    (setf (edge-reversed dep) ret)
    (push dep (aref graph from-idx))
    (push ret (aref graph to-idx))))

(defun %find-flow (src-idx dest-idx graph max-flow checked)
  "DFS"
  (declare #.OPT
           ((integer 0 #.most-positive-fixnum) src-idx dest-idx max-flow)
           (simple-bit-vector checked)
           ((simple-array list (*)) graph))
  (setf (aref checked src-idx) 1)
  (if (= src-idx dest-idx)
      max-flow
      (dolist (edge (aref graph src-idx) 0)
        (when (and (zerop (aref checked (edge-to edge)))
                   (> (edge-capacity edge) 0))
          (let ((flow (%find-flow (edge-to edge)
                                  dest-idx
                                  graph
                                  (min max-flow (edge-capacity edge))
                                  checked)))
            (declare ((integer 0 #.most-positive-fixnum) flow))
            (unless (zerop flow)
              (decf (edge-capacity edge) flow)
              (incf (edge-capacity (edge-reversed edge)) flow)
              (return flow)))))))

(defun max-flow (src-idx dest-idx graph)
  (declare #.OPT ((simple-array list (*)) graph))
  (let ((checked (make-array (length graph) :element-type 'bit :initial-element 0)))
    (loop for incr-flow of-type (integer 0 #.most-positive-fixnum)
             = (%find-flow src-idx dest-idx graph most-positive-fixnum checked)
          do (fill checked 0)
          until (zerop incr-flow)
          sum incr-flow of-type (integer 0 #.most-positive-fixnum))))

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

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

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (plan (make-array (list h w) :element-type 'bit :initial-element 0))
         (graph (make-array (* h w 2) :element-type 'list :initial-element nil))
         (start-i 0)
         (start-j 0)
         (goal-i 0)
         (goal-j 0))
    (declare (uint7 h w start-i start-j goal-i goal-j))
    (macrolet ((trans-coord (i j)
                 `(* 2 (+ (* w ,i) ,j))))
      (dotimes (i h)
        (let ((line (buffered-read-line 100)))
          (dotimes (j w)
            (case (aref line j)
              (#\o (setf (aref plan i j) 1)
               (let ((index (trans-coord i j)))
                 (push-edge index (1+ index) 1 graph)))
              (#\S (setf start-i i
                         start-j j))
              (#\T (setf goal-i i
                         goal-j j))))))
      (when (or (= start-i goal-i) (= start-j goal-j))
        (println -1)
        (return-from main))
      (let ((start-index (trans-coord start-i start-j))
            (goal-index (trans-coord goal-i goal-j)))
        (dotimes (i h)
          (loop for row-rest on (loop for j below w
                                      when (= 1 (aref plan i j))
                                      collect j)
                for init-j of-type uint7 = (car row-rest)
                for init-coord = (trans-coord i init-j)
                do (loop for dest-j of-type uint7 in (cdr row-rest)
                         for dest-coord = (trans-coord i dest-j)
                         do (push-edge (1+ init-coord) dest-coord #xffff graph)
                            (push-edge (1+ dest-coord) init-coord #xffff graph))))
        (dotimes (j w)
          (loop for col-rest on (loop for i below h
                                      when (= 1 (aref plan i j))
                                      collect i)
                for init-i of-type uint7 = (car col-rest)
                for init-coord = (trans-coord init-i j)
                do (loop for dest-i of-type uint7 in (cdr col-rest)
                         for dest-coord = (trans-coord dest-i j)
                         do (push-edge (1+ init-coord) dest-coord #xffff graph)
                            (push-edge (1+ dest-coord) init-coord #xffff graph))))
        (loop for j of-type uint7 in (loop for j below w
                                           when (= 1 (aref plan start-i j))
                                           collect j)
              do (push-edge (1+ start-index) (trans-coord start-i j) #xffff graph))
        (loop for j of-type uint7 in (loop for j below w
                                           when (= 1 (aref plan goal-i j))
                                           collect j)
              do (push-edge (1+ (trans-coord goal-i j)) goal-index #xffff graph))
        (loop for i of-type uint7 in (loop for i below h
                                           when (= 1 (aref plan i start-j))
                                           collect i)
              do (push-edge (1+ start-index) (trans-coord i start-j) #xffff graph))
        (loop for i of-type uint7 in (loop for i below h
                                           when (= 1 (aref plan i goal-j))
                                           collect i)
              do (push-edge (1+ (trans-coord i goal-j)) goal-index #xffff graph))
        (println (max-flow (1+ start-index) goal-index graph))))))

#-swank(main)

Score : 800 points

Problem Statement

There is a pond with a rectangular shape.
The pond is divided into a grid with H rows and W columns of squares.
We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).

Some of the squares in the pond contains a lotus leaf floating on the water.
On one of those leaves, S, there is a frog trying to get to another leaf T.
The state of square (i,\ j) is given to you by a character a_{ij}, as follows:

. : A square without a leaf.

o : A square with a leaf floating on the water.

S : A square with the leaf S.

T : A square with the leaf T.

The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."

Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T.
Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.

Constraints

2 ≤ H, W ≤ 100

a_{ij} is ., o, S or T.

There is exactly one S among a_{ij}.

There is exactly one T among a_{ij}.

Input

Input is given from Standard Input in the following format:

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

Output

If the objective is achievable, print the minimum necessary number of leaves to remove.
Otherwise, print -1 instead.

Sample Input 1

3 3
S.o
.o.
o.T

Sample Output 1

2

Remove the upper-right and lower-left leaves.

Sample Input 2

3 4
S...
.oo.
...T

Sample Output 2

0

Sample Input 3

4 3
.S.
.o.
.o.
.T.

Sample Output 3

-1

Sample Input 4

10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo

Sample Output 4

5


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

;; BEGIN_INSERTED_CONTENTS
(defmacro buffered-read-line (&optional (buffer-size 30) (in '*standard-input*) (terminate-char #\Space))
  "Note that the returned string will be reused."
  (let ((buffer (gensym))
        (character (gensym))
        (idx (gensym)))
    `(let ((,buffer (load-time-value (make-string ,buffer-size
                                                  :element-type 'base-char))))
       (declare (simple-base-string ,buffer))
       (loop for ,character of-type base-char =
                #-swank (code-char (read-byte ,in nil #.(char-code #\Newline)))
                #+swank (read-char ,in nil #\Newline)
             for ,idx from 0
             until (char= ,character #\Newline)
             do (setf (schar ,buffer ,idx) ,character)
             finally (when (< ,idx ,buffer-size)
                       (setf (schar ,buffer ,idx) ,terminate-char))
                     (return (values ,buffer ,idx))))))

;;;
;;; Ford-Fulkerson
;;;

(defstruct (edge (:constructor %make-edge))
  (to nil :type fixnum)
  (capacity 0 :type fixnum)
  (reversed nil :type (or null edge)))

(defun push-edge (from-idx to-idx capacity graph &key bidirectional)
  "FROM-IDX, TO-IDX := index of vertex
GRAPH := vector of list of all the edges that goes from the vertex"
  (declare #.OPT
           ((simple-array list (*)) graph))
  (let* ((dep (%make-edge :to to-idx :capacity capacity))
         (ret (%make-edge :to from-idx
                          :capacity (if bidirectional capacity 0)
                          :reversed dep)))
    (setf (edge-reversed dep) ret)
    (push dep (aref graph from-idx))
    (push ret (aref graph to-idx))))

(defun %find-flow (src-idx dest-idx graph max-flow checked)
  "DFS"
  (declare #.OPT
           ((integer 0 #.most-positive-fixnum) src-idx dest-idx max-flow)
           (simple-bit-vector checked)
           ((simple-array list (*)) graph))
  (setf (aref checked src-idx) 1)
  (if (= src-idx dest-idx)
      max-flow
      (dolist (edge (aref graph src-idx) 0)
        (when (and (zerop (aref checked (edge-to edge)))
                   (> (edge-capacity edge) 0))
          (let ((flow (%find-flow (edge-to edge)
                                  dest-idx
                                  graph
                                  (min max-flow (edge-capacity edge))
                                  checked)))
            (declare ((integer 0 #.most-positive-fixnum) flow))
            (unless (zerop flow)
              (decf (edge-capacity edge) flow)
              (incf (edge-capacity (edge-reversed edge)) flow)
              (return flow)))))))

(defun max-flow (src-idx dest-idx graph)
  (declare #.OPT ((simple-array list (*)) graph))
  (let ((checked (make-array (length graph) :element-type 'bit :initial-element 0)))
    (loop for incr-flow of-type (integer 0 #.most-positive-fixnum)
             = (%find-flow src-idx dest-idx graph most-positive-fixnum checked)
          do (fill checked 0)
          until (zerop incr-flow)
          sum incr-flow of-type (integer 0 #.most-positive-fixnum))))

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

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

(defconstant +mod+ 1000000007)

;; Hauptteil

(defun main ()
  (declare #.OPT)
  (let* ((h (read))
         (w (read))
         (plan (make-array (list h w) :element-type 'bit :initial-element 0))
         (graph (make-array (* h w 2) :element-type 'list :initial-element nil))
         (start-i 0)
         (start-j 0)
         (goal-i 0)
         (goal-j 0))
    (declare (uint7 h w start-i start-j goal-i goal-j))
    (macrolet ((trans-coord (i j)
                 `(* 2 (+ (* w ,i) ,j))))
      (dotimes (i h)
        (let ((line (buffered-read-line 100)))
          (dotimes (j w)
            (case (aref line j)
              (#\o (setf (aref plan i j) 1)
               (let ((index (trans-coord i j)))
                 (push-edge index (1+ index) 1 graph)))
              (#\S (setf start-i i
                         start-j j))
              (#\T (setf goal-i i
                         goal-j j))))))
      (when (or (= start-i goal-i) (= start-j goal-j))
        (println -1)
        (return-from main))
      (let ((start-index (trans-coord start-i start-j))
            (goal-index (trans-coord goal-i goal-j)))
        (dotimes (i h)
          (loop for row-rest on (loop for j below w
                                      when (= 1 (aref plan i j))
                                      collect j)
                for init-j of-type uint7 = (car row-rest)
                for init-coord = (trans-coord i init-j)
                do (loop for dest-j of-type uint7 in (cdr row-rest)
                         for dest-coord = (trans-coord i dest-j)
                         do (push-edge (1+ init-coord) dest-coord #xffffffff graph)
                            (push-edge (1+ dest-coord) init-coord #xffffffff graph))))
        (dotimes (j w)
          (loop for col-rest on (loop for i below h
                                      when (= 1 (aref plan i j))
                                      collect i)
                for init-i of-type uint7 = (car col-rest)
                for init-coord = (trans-coord init-i j)
                do (loop for dest-i of-type uint7 in (cdr col-rest)
                         for dest-coord = (trans-coord dest-i j)
                         do (push-edge (1+ init-coord) dest-coord #xffffffff graph)
                            (push-edge (1+ dest-coord) init-coord #xffffffff graph))))
        (loop for j of-type uint7 in (loop for j below w
                                           when (= 1 (aref plan start-i j))
                                           collect j)
              do (push-edge (1+ start-index) (trans-coord start-i j) #xffffffff graph))
        (loop for j of-type uint7 in (loop for j below w
                                           when (= 1 (aref plan goal-i j))
                                           collect j)
              do (push-edge (1+ (trans-coord goal-i j)) goal-index #xffffffff graph))
        (loop for i of-type uint7 in (loop for i below h
                                           when (= 1 (aref plan i start-j))
                                           collect i)
              do (push-edge (1+ start-index) (trans-coord i start-j) #xffffffff graph))
        (loop for i of-type uint7 in (loop for i below h
                                           when (= 1 (aref plan i goal-j))
                                           collect i)
              do (push-edge (1+ (trans-coord i goal-j)) goal-index #xffffffff graph))
        (println (max-flow (1+ start-index) goal-index graph))))))

(gc :full t)
#-swank(main)


(let ((a (read))
      (b (read))
      (c (read)))

  (format t "~A~%"
          (if (and (<= c b) (<= a c)) "Yes" "No")))

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


(let* ((n (read))
       (m (read))
       (lst (loop repeat (* 2 m)
                  collect (read))))

  (loop for i from 1 to n
        do (format t "~A~%" (count i lst))))

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2