(defun solver ()
  (let ((N (read)) (K (read))
        (array (make-array 100001 :initial-element 0)))
    (do ((i 0 (incf i))) ((= i N))
        (let ((a (read)) (b (read)))
        (incf (aref array a) b)))
    (let ((count 0))
    (do ((j 0 (incf j))) ((> j 100000))
        (incf count (aref array j))
        (when (>= count K)
          (return (format t "~A~%" j)))))))

(solver)

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


(defun read-list-from-string (str)
  (read-from-string (concatenate 'string "(" str ")")))

(defun read-num-from-string (str)
  (parse-integer str))

(defun read-list ()
  (read-list-from-string (read-line)))

(defun read-as-table (num)
  (let ((table nil)
	(lists (loop repeat num
		     for e = (read-list) then (read-list)
		     collect (cons (car e) (cadr e)))))
    (dolist (e (sort lists (lambda (x y) (<= (car x) (car y)))) (reverse table))
      (if (and table (= (caar table) (car e)))
	    (incf (cdar table) (cdr e))
	    (push e table)))))

(defun get-nth-min (num sorted)
  (let ((sorted (sort alist )))
    (labels ((inner-loop (rest acc)
	       (if (>= (+ acc (cdar rest)) num)
		   (caar rest)
		   (inner-loop (cdr rest) (+ acc (cdar rest))))))
      (inner-loop sorted 0))))

(defun solve ()
  (let* ((list (read-list))
	 (num (car list))
	 (limit (cadr list)))
    (princ (get-nth-min limit (read-as-table num)))
    (fresh-line)))

(solve)

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

Submitted source-code file size, in bytes.

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

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


(defun solver ()
  (let* ((N (read)) (K (read))
        (array-a (make-array N :fill-pointer 0))
        (array-b (make-array N :fill-pointer 0)))
    (do ((i 0 (incf i))) ((= i N))
        (vector-push (read) array-a)
        (vector-push (read) array-b))
    (let ((count 0))
    (do ((j 0 (incf j))) ((= j N))
        (incf count (aref array-b j))
        (when (>= count K)
          (return (format t "~A~%" (aref array-a j))))))))

(solver)


(defun f (a b c n)
  (if (or (oddp a)
	  (oddp b)
	  (oddp c))
      n
      (f (ash (+ b c) 1)
	 (ash (+ a c) 1)
	 (ash (+ a b) 1)
	 (+ n 1))))

(defun ff (a b c)
  (if (and (= a b) (= b c))
      (if (evenp a)
	  -1
	  0)
      (f a b c 0)))

(let ((a (read))
      (b (read))
      (c (read)))
  (format t "~a~%" (ff a b c)))

Score : 300 points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.

After the second action, they have 10, 12 and 14.

After the third action, they have 13, 12 and 11.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1


(defun split (string &key (delimiterp #'(lambda (c) (char= c #\Space))))
  (loop :for beg = (position-if-not delimiterp string)
        :then (position-if-not delimiterp string :start (1+ end))
        :for end = (and beg (position-if delimiterp string :start beg))
        :when beg :collect (subseq string beg end)
        :while end))

(defun ce (a b c count)
  (if (and (evenp a) (evenp b) (evenp c))
      (ce (/ (+ b c) 2) (/ (+ a c) 2) (/ (+ a b) 2) (+ count 1))
      count))

(destructuring-bind (a0 b0 c0) (mapcar #'parse-integer (split (read-line)))
  (format t "~d~%"
          (if (and (evenp a0)
                     (evenp b0)
                     (evenp c0)
                     (= a0 b0 c0))
              -1
              (ce a0 b0 c0 0))))


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

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

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

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

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

(defconstant +mod+ 1000000007)

;; Body

(defun main ()
  (declare #.OPT)
  (read)
  (let* ((m (the uint32 (read)))
         (table (make-array 100001 :element-type 'uint32 :initial-element 0)))
    (dotimes (i m)
      (incf (aref table (read-fixnum)))
      (incf (aref table (read-fixnum))))
    (write-line
     (if (every #'evenp table)
         "YES"
         "NO"))))

#-swank (main)

Score : 500 points

Problem Statement

Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.

First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge.

Then, Aoki gave him M queries. The i-th of them is as follows:

Increment the number written at each edge along the path connecting vertices a_i and b_i, by one.

After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number.
However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries.

Determine whether there exists a tree that has the property mentioned by Takahashi.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

1 ≤ a_i,b_i ≤ N

a_i ≠ b_i

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print YES if there exists a tree that has the property mentioned by Takahashi; print NO otherwise.

Sample Input 1

4 4
1 2
2 4
1 3
3 4

Sample Output 1

YES

For example, Takahashi's graph has the property mentioned by him if it has the following edges: 1-2, 1-3 and 1-4.
In this case, the number written at every edge will become 2.

Sample Input 2

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

Sample Output 2

NO


(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
;;;
;;; Maximum bipartite matching (Hopcroft-Karp, O(E sqrt(V)))
;;;

;; NOTE: The number of elements in the graph must be less than 2^32-1 as we use
;; (UNSIGNED-BYTE 32) here for efficiency.

;; NOTE: Pay attention to the stack size!

(defconstant +graph-inf-distance+ #xffffffff)

(defstruct (bipartite-graph
            (:constructor make-bgraph
                (size1
                 size2
                 &aux
                 (graph1 (make-array size1 :element-type 'list :initial-element nil))
                 (matching1 (make-array size1 :element-type 'fixnum :initial-element -1))
                 (matching2 (make-array size2 :element-type 'fixnum :initial-element -1))))
            (:conc-name bgraph-))
  (size1 0 :type (unsigned-byte 32))
  (size2 0 :type (unsigned-byte 32))
  (graph1 nil :type (simple-array list (*)))
  (matching1 nil :type (simple-array fixnum (*)))
  (matching2 nil :type (simple-array fixnum (*))))

(declaim (inline bgraph-add-edge!))
(defun bgraph-add-edge! (bgraph vertex1 vertex2)
  (push vertex2 (aref (bgraph-graph1 bgraph) vertex1))
  bgraph)

(defun %fill-levels (bgraph levels1 levels2 queue)
  "Does BFS and fills LEVELS."
  (declare (optimize (speed 3) (safety 0))
           ((simple-array (unsigned-byte 32) (*)) levels1 levels2 queue))
  (let ((graph1 (bgraph-graph1 bgraph))
        (matching1 (bgraph-matching1 bgraph))
        (matching2 (bgraph-matching2 bgraph))
        (q-front 0)
        (q-end 0)
        (found nil))
    (declare ((integer 0 #.most-positive-fixnum) q-front q-end))
    (labels ((enqueue (obj)
               (setf (aref queue q-end) obj)
               (incf q-end))
             (dequeue ()
               (prog1 (aref queue q-front)
                 (incf q-front))))
      (declare (inline enqueue dequeue))
      (fill levels1 +graph-inf-distance+)
      (fill levels2 +graph-inf-distance+)
      (dotimes (i (bgraph-size1 bgraph))
        (when (= -1 (aref matching1 i))
          (setf (aref levels1 i) 0)
          (enqueue i)))
      (loop until (= q-front q-end)
            for vertex = (dequeue)
            do (dolist (next (aref graph1 vertex))
                 (when (= +graph-inf-distance+ (aref levels2 next))
                   (setf (aref levels2 next) (+ 1 (aref levels1 vertex)))
                   (let ((partner (aref matching2 next)))
                     (when (= -1 partner)
                       (setq found t)
                       (return))
                     (setf (aref levels1 partner) (+ 1 (aref levels2 next)))
                     (enqueue partner))))))
    found))

(defun %find-matching (bgraph src levels1 levels2)
  "Does DFS and makes matching greedily on the residual network."
  (declare (optimize (speed 3) (safety 0))
           ((integer 0 #.most-positive-fixnum) src)
           ((simple-array (unsigned-byte 32) (*)) levels1 levels2))
  (let ((matching1 (bgraph-matching1 bgraph))
        (matching2 (bgraph-matching2 bgraph))
        (graph1 (bgraph-graph1 bgraph)))
    (labels ((dfs (v)
               (declare ((integer 0 #.most-positive-fixnum) v))
               (dolist (next (aref graph1 v))
                 (when (= (aref levels2 next) (+ 1 (aref levels1 v)))
                   (setf (aref levels2 next) +graph-inf-distance+) ; mark visited
                   (let ((partner (aref matching2 next)))
                     (when (or (= -1 partner) (dfs partner))
                       (setf (aref matching1 v) next
                             (aref matching2 next) v
                             (aref levels1 v) +graph-inf-distance+ ; mark visited
                             )
                       (return-from dfs t)))))
               (setf (aref levels1 v) +graph-inf-distance+) ; mark visited
               nil ; not matched
               ))
      (dfs src))))

(declaim (ftype (function * (values (unsigned-byte 32) &optional)) bgraph-build-matching!))
(defun bgraph-build-matching! (bgraph)
  "Makes a maximum bipartite matching and returns two vectors: correspondence
from group 1 to group 2, and correspondence from group 2 to group 1. At an
unmatched vertex, -1 is stored."
  (declare (optimize (speed 3)))
  (let* ((size1 (bgraph-size1 bgraph))
         (size2 (bgraph-size2 bgraph))
         (matching1 (bgraph-matching1 bgraph))
         (levels1 (make-array size1 :element-type '(unsigned-byte 32)))
         (levels2 (make-array size2 :element-type '(unsigned-byte 32)))
         (queue (make-array (+ size1 size2) :element-type '(unsigned-byte 32)))
         (count 0))
    (declare ((integer 0 #.most-positive-fixnum) count))
    (loop while (%fill-levels bgraph levels1 levels2 queue)
          do (dotimes (v size1)
               (when (and (= -1 (aref matching1 v))
                          (%find-matching bgraph v levels1 levels2))
                 (incf count))))
    count))

(defun coerce-to-bgraph (graph)
  "Converts adjacency lists representation of undirected graph to
BIPARTITE-GRAPH.

GRAPH := vector of adjacency lists"
  (declare (vector graph))
  (let* ((n (length graph))
         (visited (make-array n :element-type 'bit :initial-element 0))
         (colors (make-array n :element-type 'bit :initial-element 0))
         (nums (make-array n :element-type 'fixnum))
         (size0 0)
         (size1 0))
    (declare ((integer 0 #.most-positive-fixnum) size0 size1))
    (labels ((dfs (vertex color)
               (cond ((zerop (aref visited vertex))
                      (setf (aref visited vertex) 1
                            (aref colors vertex) color)
                      (if (zerop color)
                          (setf (aref nums vertex) size0
                                size0 (+ size0 1))
                          (setf (aref nums vertex) size1
                                size1 (+ size1 1)))
                      (if (= color 1)
                          (dolist (neighbor (aref graph vertex))
                            (dfs neighbor 0))
                          (dolist (neighbor (aref graph vertex))
                            (dfs neighbor 1))))
                     ((/= color (aref colors vertex))
                      (error "Not bipartite.")))))
      (dotimes (i n)
        (when (zerop (aref visited i))
          (dfs i 1)))
      (let ((bgraph (make-bgraph size0 size1)))
        (dotimes (i n)
          (when (zerop (aref colors i))
            (let ((i-num (aref nums i)))
              (dolist (j (aref graph i))
                (let ((j-num (aref nums j)))
                  (bgraph-add-edge! bgraph i-num j-num))))))
        bgraph))))

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

;;;
;;; Queue with singly linked list
;;;

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

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

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

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

(declaim (inline queue-peek))
(defun queue-peek (queue)
  (car (queue-list queue)))

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

(in-package :cl-user)

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (graph (make-array n :element-type 'list :initial-element nil)))
    (dotimes (i (- n 1))
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (push a (aref graph b))
        (push b (aref graph a))))
    (let* ((bgraph (coerce-to-bgraph graph))
           (res (bgraph-build-matching! bgraph)))
      (write-line
       (if (= (* res 2) n)
           "Second"
           "First")))))

#-swank (main)

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

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

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

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

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

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

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

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

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

Score : 900 points

Problem Statement

There is a tree with N vertices numbered 1 through N.
The i-th of the N-1 edges connects vertices a_i and b_i.

Initially, each vertex is uncolored.

Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi:

Select a vertex that is not painted yet.

If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki.

Then, after all the vertices are colored, the following procedure takes place:

Repaint every white vertex that is adjacent to a black vertex, in black.

Note that all such white vertices are repainted simultaneously, not one at a time.

If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins.
Determine the winner of the game, assuming that both persons play optimally.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i,b_i ≤ N

a_i ≠ b_i

The input graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

Print First if Takahashi wins; print Second if Aoki wins.

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Below is a possible progress of the game:

First, Takahashi paint vertex 2 white.

Then, Aoki paint vertex 1 black.

Lastly, Takahashi paint vertex 3 white.

In this case, the colors of vertices 1, 2 and 3 after the final procedure are black, black and white, resulting in Takahashi's victory.

Sample Input 2

4
1 2
2 3
2 4

Sample Output 2

First

Sample Input 3

6
1 2
2 3
3 4
2 5
5 6

Sample Output 3

Second


(let ((str (read-line)))
  (defun f (n)
    (char= (aref str (1- n)) (aref str (1+ n))))
  (if (and (f (position #\Space str :test #'char=)) (f (position #\Space str :test #'char= :from-end t)))
      (princ "YES")
      (princ "NO")))

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


(setq a(concatenate(string(read))))
(setq b(concatenate(string(read))))
(setq c(concatenate(string(read))))
(princ(if(and(char=(nth(1-(length a))a)(first b))(char=(nth(1-(length b))b)(first c)))"YES""NO"))


(let ((a (read))
      (b (read))
      (c (read))
      (flag nil))

  (loop named foo
        for i from a to (* a 100) by a
        if (= (mod i b) c) do (progn (setq flag t)
                                     (return-from foo)))

  (format t "~A~%"
          (if flag 'yes 'no)))

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


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

;; dp[i][j][k] = Maximal value for k items in {0, ..., i-1} with total weight <= j
;; Let w'_i be the weight of the item i offset by w_0 (=: w').

;; dp[i+1][j][k] max=  dp[i][j][k]
;; dp[i+1][j+w_i][k+1] max= dp[i][j][k]+v_i
;; k<=i

;; When we choose k items, the possible upper limit of the total weight is
;; W-k*w'. However, we have only to look up the weight <= Σw'_i:
;; i.e. min(W-k*w', Σw_i). Therefore the range of the weight in the DP table
;; needs to be at most 300.
(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (w (read))
         (ws (make-array n :element-type 'uint31 :initial-element 0))
         (vs (make-array n :element-type 'uint31))
         (w-offset 0))
    (declare ((integer 0 100) n)
             (uint31 w w-offset))
    (dotimes (i n)
      (if (zerop i)
          (setf w-offset (read-fixnum))
          (setf (aref ws i) (- (read-fixnum) w-offset)))
      (setf (aref vs i) (read-fixnum)))
    (let* ((virtual-w (reduce #'+ ws))
           (dp (make-array (list (1+ n) (1+ virtual-w) (1+ n))
                           :element-type 'uint62
                           :initial-element 0)))
      (declare (uint31 virtual-w))
      (dotimes (i n)
        (dotimes (j (1+ virtual-w))
          (dotimes (k (1+ i))
            (setf (aref dp (+ i 1) j k)
                  (max (aref dp (+ i 1) j k) (aref dp i j k)))
            (let ((next-w (+ j (aref ws i))))
              (when (<= next-w virtual-w)
                (setf (aref dp (+ i 1) next-w (+ k 1) )
                      (max (aref dp (+ i 1) next-w (+ k 1))
                           (+ (aref dp i j k) (aref vs i)))))))))
      (println
       (loop for k to n
             for possible-weight = (min virtual-w (- w (* k w-offset)))
             while (>= possible-weight 0)
             maximize (aref dp n possible-weight k))))))

#-swank(main)

Score : 400 points

Problem Statement

You have N items and a bag of strength W.
The i-th item has a weight of w_i and a value of v_i.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

1 ≤ N ≤ 100

1 ≤ W ≤ 10^9

1 ≤ w_i ≤ 10^9

For each i = 2,3,...,N, w_1 ≤ w_i ≤ w_1 + 3.

1 ≤ v_i ≤ 10^7

W, each w_i and v_i are integers.

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.


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

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

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

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defmacro define-cons-pack (name &rest slot-descriptions)
    (assert slot-descriptions () "~A has no slots." name)
    (labels ((extract-62bit-slots (list)
               (let ((position 0))
                 (loop for (slot-name slot-size) in list
                       while (<= (+ position slot-size) 62)
                       collect (list slot-name slot-size position)
                       do (incf position slot-size)))))
      (let* ((packer-name (intern (%concat-name "PACK" name)))
             (unpacker-macro-name (intern (%concat-name "WITH-UNPACKING" name)))
             (new-value (gensym "NEW-VALUE"))
             (tmp1 (gensym))
             (tmp2 (gensym))
             (tmp (gensym))
             (car-slots (extract-62bit-slots slot-descriptions))
             (car-revslots (reverse car-slots))
             (cdr-slots (extract-62bit-slots (nthcdr (length car-slots) slot-descriptions)))
             (cdr-revslots (reverse cdr-slots))
             (slots (append car-slots cdr-slots)))
        (assert (= (+ (length car-slots) (length cdr-slots))
                   (length slot-descriptions))
                () "Size restriction iviolated: each cell <= 62 bit, total size <= 124 bit")
        (unless (> (length cdr-slots) 0)
          (error "Whole size is too small. Use DEFINE-INTEGER-PACK instead."))
        (let ((car-width (+ (second (first car-revslots))
                            (third (first car-revslots))))
              (cdr-width (+ (second (first cdr-revslots))
                            (third (first cdr-revslots)))))
          `(progn
             (deftype ,name () '(cons (unsigned-byte ,car-width) (unsigned-byte ,cdr-width)))
             ;; define most positive integer for every slot as constant
             ,@(loop for (slot-name slot-size _) in slots
                     collect `(defconstant ,(intern (%concat+name+ "MAX" name slot-name))
                                (- (ash 1 ,slot-size) 1)))
             ;; setter and getter
             ,@(loop for slot in car-slots
                     for (slot-name slot-size slot-position) = slot
                     for accessor-name = (intern (%concat-name name slot-name))
                     append `((declaim (inline ,accessor-name (setf ,accessor-name)))
                              (defun ,accessor-name (,name)
                                (declare (type ,name ,name))
                                (ldb (byte ,slot-size ,slot-position)
                                     (the (unsigned-byte ,car-width) (car ,name))))
                              (defun (setf ,accessor-name) (,new-value ,name)
                                (declare (type ,name ,name))
                                (setf (ldb (byte ,slot-size ,slot-position)
                                           (the (unsigned-byte ,car-width) (car ,name)))
                                      ,new-value))))
             ,@(loop for slot in cdr-slots
                     for (slot-name slot-size slot-position) = slot
                     for accessor-name = (intern (%concat-name name slot-name))
                     append `((declaim (inline ,accessor-name (setf ,accessor-name)))
                              (defun ,accessor-name (,name)
                                (declare (type ,name ,name))
                                (ldb (byte ,slot-size ,slot-position)
                                     (the (unsigned-byte ,cdr-width) (cdr ,name))))
                              (defun (setf ,accessor-name) (,new-value ,name)
                                (declare (type ,name ,name))
                                (setf (ldb (byte ,slot-size ,slot-position)
                                           (the (unsigned-byte ,cdr-width) (cdr ,name)))
                                      ,new-value))))
             ;; constructor
             (declaim (inline ,packer-name))
             (defun ,packer-name ,(loop for slot in slots collect (car slot))
               (declare ,@(loop for (slot-name slot-size slot-position) in slots
                                collect `(type (unsigned-byte ,slot-size) ,slot-name)))
               (let ((,tmp1 ,(caar car-revslots))
                     (,tmp2 ,(caar cdr-revslots)))
                 (declare (type (unsigned-byte ,car-width) ,tmp1)
                          (type (unsigned-byte ,cdr-width) ,tmp2))
                 ,@(loop for (slot-name slot-size _) in (rest car-revslots)
                         collect `(setq ,tmp1 (+ ,slot-name
                                                 (the (unsigned-byte ,car-width)
                                                      (ash ,tmp1 ,slot-size)))))
                 ,@(loop for (slot-name slot-size _) in (rest cdr-revslots)
                         collect `(setq ,tmp2 (+ ,slot-name
                                                 (the (unsigned-byte ,cdr-width)
                                                      (ash ,tmp2 ,slot-size)))))
                 (cons ,tmp1 ,tmp2)))
             ;; destructuring-bind-style macro
             (defmacro ,unpacker-macro-name (vars ,name &body body)
               (check-type vars list)
               (assert (= (length vars) ,(length slots)))
               `(let* ((,',tmp ,,name)
                       (,',tmp1 (car ,',tmp))
                       (,',tmp2 (cdr ,',tmp)))
                  (declare (type (unsigned-byte ,,car-width) ,',tmp1)
                           (type (unsigned-byte ,,cdr-width) ,',tmp2))
                  (let* ,(loop for var in vars
                               for rest on ',car-slots
                               for (slot-name slot-size _) = (car rest)
                               collect `(,var
                                         (prog1 (the (unsigned-byte ,slot-size)
                                                     (ldb (byte ,slot-size 0) ,',tmp1))
                                           ,@(when (cdr rest)
                                               `((setq ,',tmp1 (ash ,',tmp1 ,(- slot-size))))))))
                    (let* ,(loop for var in (nthcdr ,(length car-slots) vars)
                                 for rest on ',cdr-slots
                                 for (slot-name slot-size _) = (car rest)
                                 collect `(,var
                                           (prog1 (the (unsigned-byte ,slot-size)
                                                       (ldb (byte ,slot-size 0) ,',tmp2))
                                             ,@(when (cdr rest)
                                                 `((setq ,',tmp2 (ash ,',tmp2 ,(- slot-size))))))))
                      ,@body))))))))))

(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 22 31 32 40 62 63 64)

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

;; Treap with implicit key for updating and querying interval.
(eval-when (:compile-toplevel :load-toplevel :execute)
  (define-cons-pack node (value- 40) (delta- 22) (value+ 40) (delta+ 22)))

(sb-int:defconstant-eqx +op-identity+
    (pack-node +max-node-value-+ +max-node-delta-+
               +max-node-value++ +max-node-delta++)
  #'equal)

(declaim (inline op))
(defun op (a b)
  (with-unpacking-node (a-value- a-delta- a-value+ a-delta+) a
    (with-unpacking-node (b-value- b-delta- b-value+ b-delta+) b
      (if (<= (- a-value- a-delta-) (- b-value- b-delta-))
          (if (<= (+ a-value+ a-delta+) (+ b-value+ b-delta+))
              (pack-node a-value- a-delta- a-value+ a-delta+)
              (pack-node a-value- a-delta- b-value+ b-delta+))
          (if (<= (+ a-value+ a-delta+) (+ b-value+ b-delta+))
              (pack-node b-value- b-delta- a-value+ a-delta+)
              (pack-node b-value- b-delta- b-value+ b-delta+))))))

(defconstant +updater-identity+ 0)

(declaim (inline updater-op))
(defun updater-op (a b)
  "Is the operator to compute and update LAZY value. A is the current LAZY value
and B is operand."
  (declare (uint40 a b))
  (+ a b))

(declaim (inline modifier-op))
(defun modifier-op (a b size)
  "Is the operator to update ACCUMULATOR (and VALUE) based on LAZY value. A is
the current ACCUMULATOR value and B is the LAZY value. SIZE is the length of the
specified interval."
  (declare (ignorable size))
  (with-unpacking-node (a-value- a-delta- a-value+ a-delta+) a
    (pack-node (min +max-node-value-+ (+ a-value- b))
               a-delta-
               (min +max-node-value++ (+ a-value+ b))
               a-delta+)))

(defstruct (itreap (:constructor %make-itreap (value priority &key left right (count 1) (accumulator value) (lazy +updater-identity+)))
                  (:copier nil)
                  (:conc-name %itreap-))
  (value +op-identity+ :type node)
  (accumulator +op-identity+ :type node)
  (lazy +updater-identity+ :type fixnum)
  (priority 0 :type (integer 0 #.most-positive-fixnum))
  (count 1 :type (integer 0 #.most-positive-fixnum)) ; size of (sub)treap
  (left nil :type (or null itreap))
  (right nil :type (or null itreap)))

(declaim (inline itreap-count))
(defun itreap-count (itreap)
  (declare ((or null itreap) itreap))
  (if itreap
      (%itreap-count itreap)
      0))

(declaim (inline itreap-accumulator))
(defun itreap-accumulator (itreap)
  (declare ((or null itreap) itreap))
  (if itreap
      (%itreap-accumulator itreap)
      +op-identity+))

(declaim (inline update-count))
(defun update-count (itreap)
  (declare (itreap itreap))
  (setf (%itreap-count itreap)
        (+ 1
           (itreap-count (%itreap-left itreap))
           (itreap-count (%itreap-right itreap)))))

(declaim (inline update-accumulator))
(defun update-accumulator (itreap)
  (declare (itreap itreap))
  (setf (%itreap-accumulator itreap)
        (if (%itreap-left itreap)
            (if (%itreap-right itreap)
                (let ((mid (op (%itreap-accumulator (%itreap-left itreap))
                               (%itreap-value itreap))))
                  (declare (dynamic-extent mid))
                  (op mid (%itreap-accumulator (%itreap-right itreap))))
                (op (%itreap-accumulator (%itreap-left itreap))
                    (%itreap-value itreap)))
            (if (%itreap-right itreap)
                (op (%itreap-value itreap)
                    (%itreap-accumulator (%itreap-right itreap)))
                (%itreap-value itreap)))))

(declaim (inline force-self))
(defun force-self (itreap)
  (declare (itreap itreap))
  (update-count itreap)
  (update-accumulator itreap))

(declaim (inline force-down))
(defun force-down (itreap)
  (declare (itreap itreap))
  (unless (eql +updater-identity+ (%itreap-lazy itreap))
    (when (%itreap-left itreap)
      (setf (%itreap-lazy (%itreap-left itreap))
            (updater-op (%itreap-lazy (%itreap-left itreap))
                        (%itreap-lazy itreap)))
      (setf (%itreap-accumulator (%itreap-left itreap))
            (modifier-op (%itreap-accumulator (%itreap-left itreap))
                         (%itreap-lazy itreap)
                         (%itreap-count (%itreap-left itreap)))))
    (when (%itreap-right itreap)
      (setf (%itreap-lazy (%itreap-right itreap))
            (updater-op (%itreap-lazy (%itreap-right itreap))
                        (%itreap-lazy itreap)))
      (setf (%itreap-accumulator (%itreap-right itreap))
            (modifier-op (%itreap-accumulator (%itreap-right itreap))
                         (%itreap-lazy itreap)
                         (%itreap-count (%itreap-right itreap)))))
    (setf (%itreap-value itreap)
          (modifier-op (%itreap-value itreap)
                       (%itreap-lazy itreap)
                       1))
    (setf (%itreap-lazy itreap) +updater-identity+)))

(defun itreap-split (itreap index)
  "Destructively splits the ITREAP into two nodes [0, INDEX) and [INDEX, N), where N
  is the number of elements of the ITREAP."
  (declare #.OPT ((integer 0 #.most-positive-fixnum) index))
  (unless (<= index (itreap-count itreap))
    (error 'invalid-itreap-index-error :index index :itreap itreap))
  (labels ((recur (itreap ikey)
             (unless itreap
               (return-from itreap-split (values nil nil)))
             (force-down itreap)
             (let ((left-count (itreap-count (%itreap-left itreap))))
               (if (<= ikey left-count)
                   (multiple-value-bind (left right)
                       (itreap-split (%itreap-left itreap) ikey)
                     (setf (%itreap-left itreap) right)
                     (force-self itreap)
                     (values left itreap))
                   (multiple-value-bind (left right)
                       (itreap-split (%itreap-right itreap) (- ikey left-count 1))
                     (setf (%itreap-right itreap) left)
                     (force-self itreap)
                     (values itreap right))))))
    (recur itreap index)))

(defun itreap-merge (left right)
  "Destructively merges two ITREAPs."
  (declare #.OPT ((or null itreap) left right))
  (cond ((null left) (when right (force-down right) (force-self right)) right)
        ((null right) (when left (force-down left) (force-self left)) left)
        (t (force-down left)
           (force-down right)
           (if (> (%itreap-priority left) (%itreap-priority right))
               (progn
                 (setf (%itreap-right left)
                       (itreap-merge (%itreap-right left) right))
                 (force-self left)
                 left)
               (progn
                 (setf (%itreap-left right)
                       (itreap-merge left (%itreap-left right)))
                 (force-self right)
                 right)))))

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

(defun %heapify (top)
  "Properly swaps the priorities of the node and its two children."
  (declare #.OPT)
  (when top
    (let ((high-priority-node top))
      (when (and (%itreap-left top)
                 (> (%itreap-priority (%itreap-left top))
                    (%itreap-priority high-priority-node)))
        (setq high-priority-node (%itreap-left top)))
      (when (and (%itreap-right top)
                 (> (%itreap-priority (%itreap-right top))
                    (%itreap-priority high-priority-node)))
        (setq high-priority-node (%itreap-right top)))
      (unless (eql high-priority-node top)
        (rotatef (%itreap-priority high-priority-node)
                 (%itreap-priority top))
        (%heapify high-priority-node)))))

(defun make-itreap (size)
  "Makes a treap of SIZE in O(SIZE) time."
  (declare #.OPT)
  (labels ((build (l r)
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (if (= l r)
                 nil
                 (let* ((mid (ash (+ l r) -1))
                        (node (%make-itreap (pack-node +max-node-value-+ mid
                                                       +max-node-value++ mid)
                                            (random most-positive-fixnum))))
                   (setf (%itreap-left node) (build l mid))
                   (setf (%itreap-right node) (build (+ mid 1) r))
                   (%heapify node)
                   (force-self node)
                   node))))
    (build 0 size)))

(defun (setf itreap-ref) (new-value itreap index)
  (declare #.OPT
           ((integer 0 #.most-positive-fixnum) index))
  (unless (< index (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index index))
  (labels ((%set (itreap index)
             (declare ((integer 0 #.most-positive-fixnum) index))
             (force-down itreap)
             (prog1
                 (let ((left-count (itreap-count (%itreap-left itreap))))
                   (cond ((< index left-count)
                          (%set (%itreap-left itreap) index))
                         ((> index left-count)
                          (%set (%itreap-right itreap) (- index left-count 1)))
                         (t (setf (%itreap-value itreap) new-value))))
               (force-self itreap))))
    (%set itreap index)
    new-value))

(defun itreap-map (function itreap)
  "Successively applies FUNCTION to ITREAP[0], ..., ITREAP[SIZE-1]."
  (declare #.OPT (function function))
  (when itreap
    (force-down itreap)
    (itreap-map function (%itreap-left itreap))
    (funcall function (%itreap-value itreap))
    (itreap-map function (%itreap-right itreap))
    (force-self itreap)))

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

(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 itreap-pprint (itreap)
;;   (write-char #\<)
;;   (itreap-map (lambda (x) (princ (caar x)) (write-char #\ )) itreap)
;;   (write-char #\>)
;;   (terpri))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (q (read))
         (a (- (read) 1))
         (b (- (read) 1))
         (xs (make-array q :element-type 'uint32))
         (itreap (make-itreap n)))
    (declare (uint32 n q a b))
    (dotimes (i q) (setf (aref xs i) (- (read-fixnum) 1)))
    (locally (declare (notinline pack-node))
      (setf (itreap-ref itreap a)
            (let ((value (abs (- (aref xs 0) b))))
              (pack-node value a value a))
            (itreap-ref itreap b)
            (let ((value (abs (- (aref xs 0) a))))
              (pack-node value b value b))))
    ;; #>itreap
    (do ((i 1 (+ i 1)))
        ((>= i q))
      (multiple-value-bind (itreap-l itreap-r) (itreap-split itreap (aref xs i))
        (let* ((left-query (itreap-accumulator itreap-l))
               (right-query (itreap-accumulator itreap-r))
               (value- (node-value- left-query))
               (delta- (node-delta- left-query))
               (value+ (node-value+ right-query))
               (delta+ (node-delta+ right-query))
               (new-value (min +max-node-value-+
                               (+ (- value- delta-) (aref xs i))
                               (- (+ value+ delta+) (aref xs i)))))
          (declare (uint40 value- value+ new-value)
                   (uint22 delta- delta+))
          (setf itreap (itreap-merge itreap-l itreap-r))
          (setf (%itreap-lazy itreap) (abs (- (aref xs (- i 1)) (aref xs i))))
          (force-down itreap)
          (force-self itreap)
          (setf (itreap-ref itreap (aref xs (- i 1)))
                (pack-node new-value (aref xs (- i 1))
                           new-value (aref xs (- i 1)))))))
    (let ((res most-positive-fixnum))
      (declare (uint62 res))
      (itreap-map (lambda (x) (setq res (min res (node-value- x)))) itreap)
      (println res))))

#-swank(main)

Score : 900 points

Problem Statement

There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.

You have two pieces, initially placed on square A and B, respectively.
You will be asked to process Q queries of the following kind, in the order received:

Given an integer x_i, move one of the two pieces of your choice to square x_i.

Here, it takes you one second to move a piece one square.
That is, the time it takes to move a piece from square X to Y is |X-Y| seconds.

Your objective is to process all the queries in the shortest possible time.

You may only move the pieces in response to queries, and you may not move both pieces at the same time.
Also, it is not allowed to rearrange the order in which queries are given.
It is, however, allowed to have both pieces in the same square at the same time.

Constraints

1 ≤ N, Q ≤ 200,000

1 ≤ A, B ≤ N

1 ≤ x_i ≤ N

Input

Input is given from Standard Input in the following format:

N Q A B
x_1 x_2 ... x_Q

Output

Let the shortest possible time to process all the queries be X seconds. Print X.

Sample Input 1

8 3 1 8
3 5 1

Sample Output 1

7

All the queries can be processed in seven seconds, by:

moving the piece at square 1 to 3

moving the piece at square 8 to 5

moving the piece at square 3 to 1

Sample Input 2

9 2 1 9
5 1

Sample Output 2

4

The piece at square 9 should be moved first.

Sample Input 3

9 2 1 9
5 9

Sample Output 3

4

The piece at square 1 should be moved first.

Sample Input 4

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

Sample Output 4

21


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

;; BEGIN_INSERTED_CONTENTS
(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 22 31 32 40 62 63 64)

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

(setf *print-circle* t)

;; Treap with implicit key for updating and querying interval.

(defconstant +inf+ #xFFFFFFFFFF)
(sb-int:defconstant-eqx +op-identity+
    (cons +inf+ +inf+)
  #'equal)

(declaim (inline op))
(defun op (a b)
  (let* ((a- (car a))
         (a+ (cdr a))
         (b- (car b))
         (b+ (cdr b))
         (a-value- (ldb (byte 40 0) a-))
         (a-delta- (ldb (byte 22 40) a-))
         (a-value+ (ldb (byte 40 0) a+))
         (a-delta+ (ldb (byte 22 40) a+))
         (b-value- (ldb (byte 40 0) b-))
         (b-delta- (ldb (byte 22 40) b-))
         (b-value+ (ldb (byte 40 0) b+))
         (b-delta+ (ldb (byte 22 40) b+)))
    (declare (uint62 a- a+ b- b+)
             (uint40 a-value- a-value+ b-value- b-value+)
             (uint22 a-delta- b-delta- a-delta+ b-delta+))
    (cons (if (<= (- a-value- a-delta-) (- b-value- b-delta-))
              (dpb a-delta- (byte 22 40) a-value-)
              (dpb b-delta- (byte 22 40) b-value-))
          (if (<= (+ a-value+ a-delta+) (+ b-value+ b-delta+))
              (dpb a-delta+ (byte 22 40) a-value+)
              (dpb b-delta+ (byte 22 40) b-value+)))))

(defconstant +updater-identity+ 0)

(declaim (inline updater-op))
(defun updater-op (a b)
  "Is the operator to compute and update LAZY value. A is the current LAZY value
and B is operand."
  (declare (uint40 a b))
  (+ a b))

(declaim (inline modifier-op))
(defun modifier-op (a b size)
  "Is the operator to update ACCUMULATOR (and VALUE) based on LAZY value. A is
the current ACCUMULATOR value and B is the LAZY value. SIZE is the length of the
specified interval."
  (declare (ignorable size))
  (let* ((a- (car a))
         (a+ (cdr a))
         (a-value- (ldb (byte 40 0) a-))
         (a-delta- (ldb (byte 22 40) a-))
         (a-value+ (ldb (byte 40 0) a+))
         (a-delta+ (ldb (byte 22 40) a+)))
    (declare (uint62 a- a+)
             (uint40 a-value- a-value+ b)
             (uint22 a-delta- a-delta+))
    (cons (dpb a-delta- (byte 22 40) (min +inf+ (+ a-value- b)))
          (dpb a-delta+ (byte 22 40) (min +inf+ (+ a-value+ b))))))

(defstruct (itreap (:constructor %make-itreap (value priority &key left right (count 1) (accumulator value) (lazy +updater-identity+)))
                  (:copier nil)
                  (:conc-name %itreap-))
  (value +op-identity+ :type (cons uint62 uint62))
  (accumulator +op-identity+ :type (cons uint62 uint62))
  (lazy +updater-identity+ :type fixnum)
  (priority 0 :type (integer 0 #.most-positive-fixnum))
  (count 1 :type (integer 0 #.most-positive-fixnum)) ; size of (sub)treap
  (left nil :type (or null itreap))
  (right nil :type (or null itreap)))

(declaim (inline itreap-count))
(defun itreap-count (itreap)
  (declare ((or null itreap) itreap))
  (if itreap
      (%itreap-count itreap)
      0))

(declaim (inline itreap-accumulator))
(defun itreap-accumulator (itreap)
  (declare ((or null itreap) itreap))
  (if itreap
      (%itreap-accumulator itreap)
      +op-identity+))

(declaim (inline update-count))
(defun update-count (itreap)
  (declare (itreap itreap))
  (setf (%itreap-count itreap)
        (+ 1
           (itreap-count (%itreap-left itreap))
           (itreap-count (%itreap-right itreap)))))

(declaim (inline update-accumulator))
(defun update-accumulator (itreap)
  (declare (itreap itreap))
  (setf (%itreap-accumulator itreap)
        (if (%itreap-left itreap)
            (if (%itreap-right itreap)
                (let ((mid (op (%itreap-accumulator (%itreap-left itreap))
                               (%itreap-value itreap))))
                  (declare (dynamic-extent mid))
                  (op mid (%itreap-accumulator (%itreap-right itreap))))
                (op (%itreap-accumulator (%itreap-left itreap))
                    (%itreap-value itreap)))
            (if (%itreap-right itreap)
                (op (%itreap-value itreap)
                    (%itreap-accumulator (%itreap-right itreap)))
                (%itreap-value itreap)))))

(declaim (inline force-self))
(defun force-self (itreap)
  (declare (itreap itreap))
  (update-count itreap)
  (update-accumulator itreap))

(declaim (inline force-down))
(defun force-down (itreap)
  (declare (itreap itreap))
  (unless (eql +updater-identity+ (%itreap-lazy itreap))
    (when (%itreap-left itreap)
      (setf (%itreap-lazy (%itreap-left itreap))
            (updater-op (%itreap-lazy (%itreap-left itreap))
                        (%itreap-lazy itreap)))
      (setf (%itreap-accumulator (%itreap-left itreap))
            (modifier-op (%itreap-accumulator (%itreap-left itreap))
                         (%itreap-lazy itreap)
                         (%itreap-count (%itreap-left itreap)))))
    (when (%itreap-right itreap)
      (setf (%itreap-lazy (%itreap-right itreap))
            (updater-op (%itreap-lazy (%itreap-right itreap))
                        (%itreap-lazy itreap)))
      (setf (%itreap-accumulator (%itreap-right itreap))
            (modifier-op (%itreap-accumulator (%itreap-right itreap))
                         (%itreap-lazy itreap)
                         (%itreap-count (%itreap-right itreap)))))
    (setf (%itreap-value itreap)
          (modifier-op (%itreap-value itreap)
                       (%itreap-lazy itreap)
                       1))
    (setf (%itreap-lazy itreap) +updater-identity+)))

(defun itreap-split (itreap index)
  "Destructively splits the ITREAP into two nodes [0, INDEX) and [INDEX, N), where N
  is the number of elements of the ITREAP."
  (declare #.OPT ((integer 0 #.most-positive-fixnum) index))
  (unless (<= index (itreap-count itreap))
    (error 'invalid-itreap-index-error :index index :itreap itreap))
  (labels ((recur (itreap ikey)
             (unless itreap
               (return-from itreap-split (values nil nil)))
             (force-down itreap)
             (let ((left-count (itreap-count (%itreap-left itreap))))
               (if (<= ikey left-count)
                   (multiple-value-bind (left right)
                       (itreap-split (%itreap-left itreap) ikey)
                     (setf (%itreap-left itreap) right)
                     (force-self itreap)
                     (values left itreap))
                   (multiple-value-bind (left right)
                       (itreap-split (%itreap-right itreap) (- ikey left-count 1))
                     (setf (%itreap-right itreap) left)
                     (force-self itreap)
                     (values itreap right))))))
    (recur itreap index)))

(defun itreap-merge (left right)
  "Destructively merges two ITREAPs."
  (declare #.OPT ((or null itreap) left right))
  (cond ((null left) (when right (force-down right) (force-self right)) right)
        ((null right) (when left (force-down left) (force-self left)) left)
        (t (force-down left)
           (force-down right)
           (if (> (%itreap-priority left) (%itreap-priority right))
               (progn
                 (setf (%itreap-right left)
                       (itreap-merge (%itreap-right left) right))
                 (force-self left)
                 left)
               (progn
                 (setf (%itreap-left right)
                       (itreap-merge left (%itreap-left right)))
                 (force-self right)
                 right)))))

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

(defun %heapify (top)
  "Properly swaps the priorities of the node and its two children."
  (declare #.OPT)
  (when top
    (let ((high-priority-node top))
      (when (and (%itreap-left top)
                 (> (%itreap-priority (%itreap-left top))
                    (%itreap-priority high-priority-node)))
        (setq high-priority-node (%itreap-left top)))
      (when (and (%itreap-right top)
                 (> (%itreap-priority (%itreap-right top))
                    (%itreap-priority high-priority-node)))
        (setq high-priority-node (%itreap-right top)))
      (unless (eql high-priority-node top)
        (rotatef (%itreap-priority high-priority-node)
                 (%itreap-priority top))
        (%heapify high-priority-node)))))

(defun make-itreap (size)
  "Makes a treap of SIZE in O(SIZE) time."
  (declare #.OPT)
  (labels ((build (l r)
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (if (= l r)
                 nil
                 (let* ((mid (ash (+ l r) -1))
                        (node (%make-itreap (cons (dpb mid (byte 22 40) +inf+)
                                                  (dpb mid (byte 22 40) +inf+))
                                            (random most-positive-fixnum))))
                   (setf (%itreap-left node) (build l mid))
                   (setf (%itreap-right node) (build (+ mid 1) r))
                   (%heapify node)
                   (force-self node)
                   node))))
    (build 0 size)))

(defun (setf itreap-ref) (new-value itreap index)
  (declare #.OPT
           ((integer 0 #.most-positive-fixnum) index))
  (unless (< index (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index index))
  (labels ((%set (itreap index)
             (declare ((integer 0 #.most-positive-fixnum) index))
             (force-down itreap)
             (prog1
                 (let ((left-count (itreap-count (%itreap-left itreap))))
                   (cond ((< index left-count)
                          (%set (%itreap-left itreap) index))
                         ((> index left-count)
                          (%set (%itreap-right itreap) (- index left-count 1)))
                         (t (setf (%itreap-value itreap) new-value))))
               (force-self itreap))))
    (%set itreap index)
    new-value))

(defun itreap-map (function itreap)
  "Successively applies FUNCTION to ITREAP[0], ..., ITREAP[SIZE-1]."
  (declare #.OPT (function function))
  (when itreap
    (force-down itreap)
    (itreap-map function (%itreap-left itreap))
    (funcall function (%itreap-value itreap))
    (itreap-map function (%itreap-right itreap))
    (force-self itreap)))

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

(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 itreap-pprint (itreap)
;;   (write-char #\<)
;;   (itreap-map (lambda (x) (princ (caar x)) (write-char #\ )) itreap)
;;   (write-char #\>)
;;   (terpri))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (q (read))
         (a (- (read) 1))
         (b (- (read) 1))
         (xs (make-array q :element-type 'uint32))
         (itreap (make-itreap n)))
    (declare (uint32 n q a b))
    (dotimes (i q) (setf (aref xs i) (- (read-fixnum) 1)))
    (setf (itreap-ref itreap a)
          (let ((value (abs (- (aref xs 0) b))))
            (cons (dpb a (byte 22 40) value) (dpb a (byte 22 40) value)))
          (itreap-ref itreap b)
          (let ((value (abs (- (aref xs 0) a))))
            (cons (dpb b (byte 22 40) value) (dpb b (byte 22 40) value))))
    ;; #>itreap
    (do ((i 1 (+ i 1)))
        ((>= i q))
      (multiple-value-bind (itreap-l itreap-r) (itreap-split itreap (aref xs i))
        (let* ((left-query (itreap-accumulator itreap-l))
               (right-query (itreap-accumulator itreap-r))
               (value- (ldb (byte 40 0) (the uint62 (car left-query))))
               (delta- (ldb (byte 22 40) (the uint62 (car left-query))))
               (value+ (ldb (byte 40 0) (the uint62 (cdr right-query))))
               (delta+ (ldb (byte 22 40) (the uint62 (cdr right-query))))
               (new-value (min +inf+
                               (+ (- value- delta-) (aref xs i))
                               (- (+ value+ delta+) (aref xs i)))))
          (declare (uint40 value- value+ new-value)
                   (uint22 delta- delta+))
          (setf itreap (itreap-merge itreap-l itreap-r))
          (setf (%itreap-lazy itreap) (abs (- (aref xs (- i 1)) (aref xs i))))
          (force-down itreap)
          (force-self itreap)
          (setf (itreap-ref itreap (aref xs (- i 1)))
                (cons (dpb (aref xs (- i 1)) (byte 22 40) new-value)
                      (dpb (aref xs (- i 1)) (byte 22 40) new-value))))))
    (let ((res most-positive-fixnum))
      (declare (uint62 res))
      (itreap-map (lambda (x) (setq res (min res (ldb (byte 40 0) (car x))))) itreap)
      (println res))))

#-swank(main)


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

  (format t "~A~%"
          (cond ((> a b) "GREATER")
                ((= a b) "EQUAL")
                (t "LESS"))))

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


(defun br()
        (princ '#\newline))

(defun solve()
        (let ((a (read)) (b (read)))
                (cond ((< a b)
                        (princ 'LESS))
                      ((> a b)
                        (princ 'GREATER))
                      (t
                        (princ 'EQUAL)))
                (br)))

(solve)


(let ((a (parse-integer (read-line)))
      (b (parse-integer (read-line))))
  (format t "~a~%"
          (cond
            ((> a b) "GREATER")
            ((< a b) "LESS")
            (t "EQUAL"))))


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

(defconstant +mod+ 1000000007)

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

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

;;; Utils

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

(declaim (inline fast-sort))
(defmethod fast-sort ((sequence list) &key (test #'<))
  (declare (inline sort)
           (inline sb-impl::stable-sort-list))
  (sort sequence (lambda (x y)
                   (funcall test x y))))

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

(defmacro read-numbers-to-array (size)
  `(make-array ,size :initial-contents :element-type 'fixnum (loop repeat ,size collect (read))))

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

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

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

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

;;; Body

(defun cumlative-sum (xs &optional (acc '(0)))
  (if (null xs)
      (reverse acc)
      (cumlative-sum (rest xs) (cons (+ (first xs)
                                        (first acc))
                                     acc))))

(defun calc (a first-plus-p &optional (s 0) (res 0))
  (loop for x in a do
       (when (and (>= (+ s x) 0)
                  (not first-plus-p))
         (incf res (1+ (abs (+ s x))))
         (decf s (1+ (abs (+ s x)))))
       (when (and (<= (+ s x) 0)
                  first-plus-p)
         (incf res (1+ (abs (+ s x))))
         (incf s (1+ (abs (+ s x)))))
       (setf first-plus-p (not first-plus-p))
     finally
       (return res)))

(defun solve (a)
  (declare (list a))
  (let ((cum (cumlative-sum a)))
    (declare (list a))
    (the fixnum
         (min (calc (rest cum) t)
              (calc (rest cum) nil)))))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (a (read-numbers-to-list n)))
    (declare (fixnum n)
             ((array fixnum 1) a))
    (format t "~a~&" (solve a))))

#-swank (main)

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each 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 necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


(defun solver ()
  (let* ((n (read))
         (numv (make-array n :fill-pointer 0))
         (sum 0) (presum 0) (count 0))
    (loop repeat n
          do (vector-push (read) numv))
    (loop for x across numv
          do (incf sum x)
          (loop
            (cond ((and (zerop sum) (plusp presum))
                   (incf count) (decf sum))
                  ((and (zerop sum) (minusp presum))
                   (incf count) (incf sum))
                  ((and (plusp sum) (plusp presum))
                   (incf count (1+ sum)) (decf sum (1+ sum)))
                  ((and (plusp sum) (minusp presum))
                   (return))
                  ((and (minusp sum) (plusp presum))
                   (return))
                  ((and (minusp sum) (minusp presum))
                   (incf count (1+ (abs sum))) (incf sum (1+ (abs sum))))
                  (t (return))))
          (setf presum sum))
    (format t "~A~%" count)))

(solver)


(defun read-num (&optional (stream *standard-input*))
  (parse-integer (read-line stream)))

(defun read-list-from-string (str)
  (read-from-string (concatenate 'string "(" str ")")))

(defun read-list (&optional (stream *standard-input*))
  (read-list-from-string (read-line stream)))

(defun satisfy-num (acc val)
  (if (> acc 0)
      (if (< (+ acc val) 0)
	  0
	  (- (+ 1 val acc)))
      (if (> (+ acc val) 0)
	  0
	  (- 1 val acc))))

(defun count-shift (list)
  (let ((acc (car list))
	(sum 0))
    (dolist (e (cdr list) sum)
      (let ((shift (satisfy-num acc e)))
	(incf sum (abs shift))
	(incf acc (+ e shift))))))

(defun solve (list)
  (format t "~D~%" (count-shift list)))
(read-num)
(solve (read-list))


Score : 500 points

Problem Statement

Alice and Brown loves games. Today, they will play the following game.

In this game, there are two piles initially consisting of X and Y stones, respectively.
Alice and Bob alternately perform the following operation, starting from Alice:

Take 2i stones from one of the piles. Then, throw away i of them, and put the remaining i in the other pile. Here, the integer i (1≤i) can be freely chosen as long as there is a sufficient number of stones in the pile.

The player who becomes unable to perform the operation, loses the game.

Given X and Y, determine the winner of the game, assuming that both players play optimally.

Constraints

0 ≤ X, Y ≤ 10^{18}

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the winner: either Alice or Brown.

Sample Input 1

2 1

Sample Output 1

Brown

Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory.

Sample Input 2

5 0

Sample Output 2

Alice

Sample Input 3

0 0

Sample Output 3

Brown

Sample Input 4

4 8

Sample Output 4

Alice


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

;; BEGIN_INSERTED_CONTENTS
(defmacro with-buffered-stdout (&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
                                  (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

(declaim (inline println-sequence))
(defun println-sequence (sequence &optional (out *standard-output*))
  (let ((init t))
    (sequence:dosequence (x sequence)
      (if init
          (setq init nil)
          (write-char #\  out))
      (princ x out))
    (terpri out)))

(defun main ()
  (let* ((n (read))
         (m (read))
         (graph (make-array n :element-type 'list :initial-element nil))
         (table (make-array n :element-type 'bit :initial-element 0)))
    (declare (uint32 n m))
    (dotimes (i m)
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (push a (aref graph b))
        (push b (aref graph a))))
    (labels ((recur (v)
               (declare (uint32 v))
               (setf (aref table v) 1)
               (dolist (neighbor (aref graph v) (list v))
                 (when (zerop (aref table neighbor))
                   (return (cons v (recur neighbor)))))))
      (let* ((path1 (recur 0))
             (path2 (recur 0))
             (res (append (nreverse (cdr path1)) path2)))
        (println (length res))
        (with-buffered-stdout
          (println-sequence res))))))

#-swank (main)

Score : 500 points

Problem Statement

You are given a connected undirected simple graph, which has N vertices and M edges.
The vertices are numbered 1 through N, and the edges are numbered 1 through M.
Edge i connects vertices A_i and B_i.
Your task is to find a path that satisfies the following conditions:

The path traverses two or more vertices.

The path does not traverse the same vertex more than once.

A vertex directly connected to at least one of the endpoints of the path, is always contained in the path.

It can be proved that such a path always exists.
Also, if there are more than one solution, any of them will be accepted.

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

The given graph is connected and simple (that is, for every pair of vertices, there is at most one edge that directly connects them).

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Find one path that satisfies the conditions, and print it in the following format.
In the first line, print the count of the vertices contained in the path.
In the second line, print a space-separated list of the indices of the vertices, in order of appearance in the path.

Sample Input 1

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

Sample Output 1

4
2 3 1 4

There are two vertices directly connected to vertex 2: vertices 3 and 4.
There are also two vertices directly connected to vertex 4: vertices 1 and 2.
Hence, the path 2 → 3 → 1 → 4 satisfies the conditions.

Sample Input 2

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

Sample Output 2

7
1 2 3 4 5 6 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))))))))

(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

(declaim (inline count-collision))
(defun count-collision (anticlock clock l time)
  (if (< (* 2 time) (mod (- anticlock clock) l))
      0
      (let ((remain (- (* 2 time) (mod (- anticlock clock) l))))
        (+ 1 (floor remain l)))))

(defun main ()
  (declare #.OPT (inline sort))
  (let* ((n (read))
         (l (read))
         (time (read))
         (inits (make-array n :element-type 'uint32))
         (dirs (make-array n :element-type 'bit)))
    (declare (uint32 n l time))
    (dotimes (i n) (setf (aref inits i) (read-fixnum)
                         (aref dirs i) (logand (read-fixnum) 1)))
    (let* ((count0 (loop for i below n
                         unless (= (aref dirs 0) (aref dirs i))
                         sum (if (zerop (aref dirs 0))
                                 (count-collision (aref inits 0) (aref inits i) l time)
                                 (count-collision (aref inits i) (aref inits 0) l time))
                         of-type uint32))
           (end-index (mod (if (zerop (aref dirs 0))
                               (- count0)
                               count0)
                           n))
           (ends (make-array n :element-type 'uint32))
           (end0 (mod (+ (aref inits 0)
                         (if (zerop (aref dirs 0))
                             (- time)
                             time))
                      l)))
      (dotimes (i n)
        (setf (aref ends i)
              (mod (+ (aref inits i)
                      (if (zerop (aref dirs i))
                          (- time)
                          time))
                   l)))
      (setf ends (sort ends #'<))
      (let ((end0-pos (position end0 ends))
            (res (make-array n :element-type 'uint32)))
        (cond ((and (= (aref ends end0-pos) (aref ends (mod (+ end0-pos 1) n)))
                    (= 1 (aref dirs 0)))
               (setf end0-pos (mod (+ end0-pos 1) n)))
              ((and (= (aref ends end0-pos) (aref ends (mod (- end0-pos 1) n)))
                    (= 0 (aref dirs 0)))
               (setf end0-pos (mod (- end0-pos 1) n))))
        (let ((actual-index (mod (- end0-pos end-index) n)))
          (loop for i below n
                do (setf (aref res i)
                         (aref ends (mod (+ actual-index i) n))))
          (with-output-buffer
            (map () #'println res)))))))

#-swank(main)

Score : 700 points

Problem Statement

There is a circle with a circumference of L.
Each point on the circumference has a coordinate value, which represents the arc length from a certain reference point clockwise to the point.
On this circumference, there are N ants.
These ants are numbered 1 through N in order of increasing coordinate, and ant i is at coordinate X_i.

The N ants have just started walking.
For each ant i, you are given the initial direction W_i. Ant i is initially walking clockwise if W_i is 1; counterclockwise if W_i is 2.
Every ant walks at a constant speed of 1 per second.
Sometimes, two ants bump into each other.
Each of these two ants will then turn around and start walking in the opposite direction.

For each ant, find its position after T seconds.

Constraints

All input values are integers.

1 \leq N \leq 10^5

1 \leq L \leq 10^9

1 \leq T \leq 10^9

0 \leq X_1 < X_2 < ... < X_N \leq L - 1

1 \leq W_i \leq 2

Input

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

N L T
X_1 W_1
X_2 W_2
:
X_N W_N

Output

Print N lines.
The i-th line should contain the coordinate of ant i after T seconds. Here, each coordinate must be between 0 and L-1, inclusive.

Sample Input 1

3 8 3
0 1
3 2
6 1

Sample Output 1

1
3
0

1.5 seconds after the ants start walking, ant 1 and 2 bump into each other at coordinate 1.5.
1 second after that, ant 1 and 3 bump into each other at coordinate 0.5.
0.5 seconds after that, that is, 3 seconds after the ants start walking, ants 1, 2 and 3 are at coordinates 1, 3 and 0, respectively.

Sample Input 2

4 20 9
7 2
9 1
12 1
18 1

Sample Output 2

7
18
18
1


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

(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 count-collision (anticlock clock l time)
  (if (< (* 2 time) (mod (- anticlock clock) l))
      0
      (let ((remain (- (* 2 time) (mod (- anticlock clock) l))))
        (+ 1 (floor remain l)))))

(defun main ()
  (let* ((n (read))
         (l (read))
         (time (read))
         (inits (make-array n :element-type 'uint32))
         (dirs (make-array n :element-type 'bit)))
    (dotimes (i n) (setf (aref inits i) (read-fixnum)
                         (aref dirs i) (mod (read-fixnum) 2)))
    (let* ((count0 (loop for i below n
                         unless (= (aref dirs 0) (aref dirs i))
                         sum (if (zerop (aref dirs 0))
                                 (count-collision (aref inits 0) (aref inits i) l time)
                                 (count-collision (aref inits i) (aref inits 0) l time))))
           (end-index (mod (if (zerop (aref dirs 0))
                               (- count0)
                               count0)
                           n))
           (ends (make-array n :element-type 'uint32))
           (end0 (mod (+ (aref inits 0)
                         (if (zerop (aref dirs 0))
                             (- time)
                             time))
                      l)))
      (dotimes (i n)
        (setf (aref ends i)
              (mod (+ (aref inits i)
                      (if (zerop (aref dirs i))
                          (- time)
                          time))
                   l)))
      (setf ends (sort ends #'<))
      (let ((actual-index (mod (- (position end0 ends) end-index) n))
            (res (make-array n :element-type 'uint32)))
        (when (= (aref ends actual-index) (aref ends (mod (+ actual-index 1) n)))
          (when (= 1 (aref dirs 0))
            (setf actual-index (mod (+ actual-index 1) n))))
        (when (= (aref ends actual-index) (aref ends (mod (- actual-index 1) n)))
          (when (= 1 (aref dirs 0))
            (setf actual-index (mod (- actual-index 1) n))))
        (loop for i below n
              do (setf (aref res i)
                       (aref ends (mod (+ actual-index i) n))))
        (map () #'println res)
        ))))

#-swank(main)