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

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

;;;
;;; Binary heap
;;;

(define-condition heap-empty-error (simple-error)
  ((heap :initarg :heap :reader heap-empty-error-heap))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to pop empty heap ~W" (heap-empty-error-heap condition)))))

(define-condition heap-full-error (simple-error)
  ((heap :initarg :heap :reader heap-full-error-heap)
   (item :initarg :item :reader heap-full-error-item))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to push item ~W to full heap ~W"
             (heap-full-error-item condition)
             (heap-full-error-heap condition)))))

(defmacro define-binary-heap (name &key (order '#'>) (element-type 'fixnum))
  "Defines the binary heap specialized for the given order and the element
type. This macro defines a structure of the name NAME and relevant functions:
MAKE-<NAME>, <NAME>-PUSH, <NAME>-POP, <NAME>-REINITIALIZE, <NAME>-EMPTY-P,
<NAME>-COUNT, and <NAME>-PEEK."
  (check-type name symbol)
  (let* ((string-name (string name))
         (fname-push (intern (format nil "~A-PUSH" string-name)))
         (fname-pop (intern (format nil "~A-POP" string-name)))
         (fname-reinitialize (intern (format nil "~A-REINITIALIZE" string-name)))
         (fname-empty-p (intern (format nil "~A-EMPTY-P" string-name)))
         (fname-count (intern (format nil "~A-COUNT" string-name)))
         (fname-peek (intern (format nil "~A-PEEK" string-name)))
         (fname-make (intern (format nil "MAKE-~A" string-name)))
         (acc-position (intern (format nil "~A-POSITION" string-name)))
         (acc-data (intern (format nil "~A-DATA" string-name))))
    `(progn
       (defstruct (,name
                   (:constructor ,fname-make
                       (size
                        &aux (data ,(if (eql element-type '*)
                                        `(make-array (1+ size))
                                        `(make-array (1+ size) :element-type ',element-type))))))
         (data #() :type (simple-array ,element-type (*)) :read-only t)
         (position 1 :type (integer 1 #.most-positive-fixnum)))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-push))
       (defun ,fname-push (obj heap)
         "Adds OBJ to the end of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((update (pos)
                        (declare (optimize (speed 3) (safety 0)))
                        (unless (= pos 1)
                          (let ((parent-pos (ash pos -1)))
                            (when (funcall ,order (aref data pos) (aref data parent-pos))
                              (rotatef (aref data pos) (aref data parent-pos))
                              (update parent-pos))))))
               (unless (< position (length data))
                 (error 'heap-full-error :heap heap :item obj))
               (setf (aref data position) obj)
               (update position)
               (incf position)
               heap))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-pop))
       (defun ,fname-pop (heap)
         "Removes and returns the element at the top of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((update (pos)
                        (declare (optimize (speed 3) (safety 0))
                                 ((integer 1 #.most-positive-fixnum) pos))
                        (let* ((child-pos1 (+ pos pos))
                               (child-pos2 (1+ child-pos1)))
                          (when (<= child-pos1 position)
                            (if (<= child-pos2 position)
                                (if (funcall ,order (aref data child-pos1) (aref data child-pos2))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                      (rotatef (aref data pos) (aref data child-pos1))
                                      (update child-pos1))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos2))
                                      (rotatef (aref data pos) (aref data child-pos2))
                                      (update child-pos2)))
                                (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                  (rotatef (aref data pos) (aref data child-pos1))))))))
               (when (= position 1)
                 (error 'heap-empty-error :heap heap))
               (prog1 (aref data 1)
                 (decf position)
                 (setf (aref data 1) (aref data position))
                 (update 1))))))

       (declaim (inline ,fname-reinitialize))
       (defun ,fname-reinitialize (heap)
         "Makes HEAP empty."
         (setf (,acc-position heap) 1)
         heap)

       (declaim (inline ,fname-empty-p))
       (defun ,fname-empty-p (heap)
         "Returns true iff HEAP is empty."
         (= 1 (,acc-position heap)))

       (declaim (inline ,fname-count))
       (defun ,fname-count (heap)
         "Returns the current number of the elements in HEAP."
         (- (,acc-position heap) 1))

       (declaim (inline ,fname-peek))
       (defun ,fname-peek (heap)
         "Returns the topmost element of HEAP."
         (if (= 1 (,acc-position heap))
             (error 'heap-empty-error :heap heap)
             (aref (,acc-data heap) 1))))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +inf+ #xffffffff)
;; dist . v
(define-binary-heap heap
  :order (lambda (x y)
           (< (the uint32 (car x)) (the uint32 (car y))))
  :element-type (cons uint32 uint32))

(defun min-cycle-cost (src dest n graph que)
  (declare #.OPT
           ((simple-array list (*)) graph)
           (uint32 n src dest))
  (heap-reinitialize que)
  (let ((dists (make-array (* 2 n) :element-type 'uint32 :initial-element +inf+)))
    (heap-push (cons 0 src) que)
    (loop until (heap-empty-p que)
          for (dist . current) of-type (uint32 . uint32) = (heap-pop que)
          when (< dist (aref dists current))
          do (setf (aref dists current) dist)
             (dolist (neighbor (aref graph current))
               (declare (uint32 neighbor))
               (let ((cost (if (= neighbor (+ current n)) 0 1)))
                 (when (< (+ dist cost) (aref dists neighbor))
                   (heap-push (cons (+ dist cost) neighbor) que)))))
    (values (aref dists dest) dists)))

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (m (read))
         ;; in : out
         (graph (make-array (* 2 n) :element-type 'list :initial-element nil))
         (que (make-heap (+ m n n)))
         (min-len +inf+)
         (min-src 0)
         min-dists)
    (declare (uint32 n m min-len min-src))
    (dotimes (i n)
      (push (+ i n) (aref graph i)))
    (dotimes (i m)
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (declare (uint32 a b))
        (push b (aref graph (+ a n)))))
    (dotimes (i n)
      (let ((src (+ i n))
            (dest i))
        (multiple-value-bind (len dists) (min-cycle-cost src dest n graph que)
          (declare (uint32 len))
          (when (< len min-len)
            (setq min-len len
                  min-src src
                  min-dists dists)))))
    (if (= min-len +inf+)
        (println -1)
        (let* ((marked (make-array (* 2 n) :element-type 'bit :initial-element 0))
               (min-dest (- min-src n))
               (path
                 (block dfs
                   (sb-int:named-let recur ((v min-src) (path (list min-src)))
                     (when (= v min-dest)
                       (return-from dfs (nreverse path)))
                     (setf (aref marked v) 1)
                     (dolist (neighbor (aref graph v))
                       (when (and (zerop (aref marked neighbor))
                                  (= (aref min-dists neighbor)
                                     (+ (aref min-dists v)
                                        (if (= neighbor (+ v n)) 0 1))))
                         (recur neighbor (cons neighbor path))))))))
          (declare ((simple-array uint32 (*)) min-dists))
          (println min-len)
          (dolist (v path)
            (declare (uint32 v))
            (when (< v n)
              (println (+ 1 v))))))))

#-swank (main)

Score : 600 points

Problem Statement

Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.

Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

Notes

For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:

V' is a (non-empty) subset of V.

E' is the set of all the edges in E that have both endpoints in V'.

Constraints

1 \leq N \leq 1000

0 \leq M \leq 2000

1 \leq A_i,B_i \leq N

A_i \neq B_i

All pairs (A_i, B_i) are distinct.

All values in input are integers.

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

If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:

K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

Sample Input 1

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

Sample Output 1

3
1
2
4

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

Sample Input 2

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

Sample Output 2

-1

There is no induced subgraph of G that satisfies the condition.

Sample Input 3

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

Sample Output 3

4
2
3
4
5


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

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

;;;
;;; Binary heap
;;;

(define-condition heap-empty-error (simple-error)
  ((heap :initarg :heap :reader heap-empty-error-heap))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to pop empty heap ~W" (heap-empty-error-heap condition)))))

(define-condition heap-full-error (simple-error)
  ((heap :initarg :heap :reader heap-full-error-heap)
   (item :initarg :item :reader heap-full-error-item))
  (:report
   (lambda (condition stream)
     (format stream "Attempted to push item ~W to full heap ~W"
             (heap-full-error-item condition)
             (heap-full-error-heap condition)))))

(defmacro define-binary-heap (name &key (order '#'>) (element-type 'fixnum))
  "Defines the binary heap specialized for the given order and the element
type. This macro defines a structure of the name NAME and relevant functions:
MAKE-<NAME>, <NAME>-PUSH, <NAME>-POP, <NAME>-REINITIALIZE, <NAME>-EMPTY-P,
<NAME>-COUNT, and <NAME>-PEEK."
  (check-type name symbol)
  (let* ((string-name (string name))
         (fname-push (intern (format nil "~A-PUSH" string-name)))
         (fname-pop (intern (format nil "~A-POP" string-name)))
         (fname-reinitialize (intern (format nil "~A-REINITIALIZE" string-name)))
         (fname-empty-p (intern (format nil "~A-EMPTY-P" string-name)))
         (fname-count (intern (format nil "~A-COUNT" string-name)))
         (fname-peek (intern (format nil "~A-PEEK" string-name)))
         (fname-make (intern (format nil "MAKE-~A" string-name)))
         (acc-position (intern (format nil "~A-POSITION" string-name)))
         (acc-data (intern (format nil "~A-DATA" string-name))))
    `(progn
       (defstruct (,name
                   (:constructor ,fname-make
                       (size
                        &aux (data ,(if (eql element-type '*)
                                        `(make-array (1+ size))
                                        `(make-array (1+ size) :element-type ',element-type))))))
         (data #() :type (simple-array ,element-type (*)) :read-only t)
         (position 1 :type (integer 1 #.most-positive-fixnum)))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-push))
       (defun ,fname-push (obj heap)
         "Adds OBJ to the end of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((update (pos)
                        (declare (optimize (speed 3) (safety 0)))
                        (unless (= pos 1)
                          (let ((parent-pos (ash pos -1)))
                            (when (funcall ,order (aref data pos) (aref data parent-pos))
                              (rotatef (aref data pos) (aref data parent-pos))
                              (update parent-pos))))))
               (unless (< position (length data))
                 (error 'heap-full-error :heap heap :item obj))
               (setf (aref data position) obj)
               (update position)
               (incf position)
               heap))))

       (declaim #+sbcl (sb-ext:maybe-inline ,fname-pop))
       (defun ,fname-pop (heap)
         "Removes and returns the element at the top of HEAP."
         (declare (optimize (speed 3))
                  (type ,name heap))
         (symbol-macrolet ((position (,acc-position heap)))
           (let ((data (,acc-data heap)))
             (declare ((simple-array ,element-type (*)) data))
             (labels ((update (pos)
                        (declare (optimize (speed 3) (safety 0))
                                 ((integer 1 #.most-positive-fixnum) pos))
                        (let* ((child-pos1 (+ pos pos))
                               (child-pos2 (1+ child-pos1)))
                          (when (<= child-pos1 position)
                            (if (<= child-pos2 position)
                                (if (funcall ,order (aref data child-pos1) (aref data child-pos2))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                      (rotatef (aref data pos) (aref data child-pos1))
                                      (update child-pos1))
                                    (unless (funcall ,order (aref data pos) (aref data child-pos2))
                                      (rotatef (aref data pos) (aref data child-pos2))
                                      (update child-pos2)))
                                (unless (funcall ,order (aref data pos) (aref data child-pos1))
                                  (rotatef (aref data pos) (aref data child-pos1))))))))
               (when (= position 1)
                 (error 'heap-empty-error :heap heap))
               (prog1 (aref data 1)
                 (decf position)
                 (setf (aref data 1) (aref data position))
                 (update 1))))))

       (declaim (inline ,fname-reinitialize))
       (defun ,fname-reinitialize (heap)
         "Makes HEAP empty."
         (setf (,acc-position heap) 1)
         heap)

       (declaim (inline ,fname-empty-p))
       (defun ,fname-empty-p (heap)
         "Returns true iff HEAP is empty."
         (= 1 (,acc-position heap)))

       (declaim (inline ,fname-count))
       (defun ,fname-count (heap)
         "Returns the current number of the elements in HEAP."
         (- (,acc-position heap) 1))

       (declaim (inline ,fname-peek))
       (defun ,fname-peek (heap)
         "Returns the topmost element of HEAP."
         (if (= 1 (,acc-position heap))
             (error 'heap-empty-error :heap heap)
             (aref (,acc-data heap) 1))))))

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +inf+ #xffffffff)
;; dist . v
(define-binary-heap heap
  :order (lambda (x y)
           (< (the uint32 (car x)) (the uint32 (car y))))
  :element-type list)

(defun min-cycle-cost (src dest n graph que)
  (declare ((simple-array list (*)) graph)
           (uint32 n src dest))
  (heap-reinitialize que)
  (let ((dists (make-array (* 2 n) :element-type 'uint32 :initial-element +inf+)))
    (heap-push (cons 0 src) que)
    (loop until (heap-empty-p que)
          for (dist . current) = (heap-pop que)
          when (< dist (aref dists current))
          do (setf (aref dists current) dist)
             (dolist (neighbor (aref graph current))
               (let ((cost (if (= neighbor (+ current n)) 0 1)))
                 (when (< (+ dist cost) (aref dists neighbor))
                   (heap-push (cons (+ dist cost) neighbor) que)))))
    (values (aref dists dest) dists)))

(defun min-cycle (src n graph que)
  (declare ((simple-array list (*)) graph)
           (uint32 n src))
  (heap-reinitialize que)
  (let ((dists (make-array (* 2 n) :element-type 'uint32 :initial-element +inf+))
        (paths (make-array (* 2 n) :element-type 'list :initial-element nil)))
    (heap-push (list 0 src (list src)) que)
    (loop until (heap-empty-p que)
          for (dist current path) = (heap-pop que)
          when (< dist (aref dists current))
          do (setf (aref dists current) dist
                   (aref paths current) path)
             (dolist (neighbor (aref graph current))
               (let ((cost (if (= neighbor (+ current n)) 0 1)))
                 (when (< (+ dist cost) (aref dists neighbor))
                   (heap-push (list (+ dist cost) neighbor (cons neighbor path)) que)))))
    paths))

(defun main ()
  (let* ((n (read))
         (m (read))
         ;; in : out
         (graph (make-array (* 2 n) :element-type 'list :initial-element nil))
         (revgraph (make-array (* 2 n) :element-type 'list :initial-element nil))
         (que (make-heap (+ m n n)))
         (min-value +inf+)
         (min-src 0)
         min-dists)
    (declare (uint32 n m min-value min-src))
    (dotimes (i n)
      (push (+ i n) (aref graph i))
      (push i (aref revgraph (+ i n))))
    (dotimes (i m)
      (let ((a (- (read-fixnum) 1))
            (b (- (read-fixnum) 1)))
        (declare (uint32 a b))
        (push b (aref graph (+ a n)))
        (push (+ a n) (aref revgraph b))))
    (dotimes (i n)
      (let ((src (+ i n))
            (dest i))
        (multiple-value-bind (res dists) (min-cycle-cost src dest n graph que)
          (when (< res min-value)
            (setf min-value res
                  min-src src
                  min-dists dists)))))
    (if (= min-value +inf+)
        (println -1)
        (let* ((paths (min-cycle min-src n graph que))
               (min-dest (- min-src n))
               (path (reverse (aref paths min-dest))))
          (println min-value)
          (dolist (v path)
            (when (< v n)
              (println (+ 1 v))))))))

#-swank (main)

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

Submitted source-code file size, in bytes.

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

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


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

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

;; TODO: non-global handling

(defconstant +binom-size+ 1100000)
(defconstant +binom-mod+ +mod+)

(declaim ((simple-array (unsigned-byte 32) (*)) *inv*))
(defparameter *inv* (make-array +binom-size+ :element-type '(unsigned-byte 32))
  "table of inverses of non-negative integers")

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

(initialize-binom)

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

;;;
;;; Arithmetic operations with static modulus
;;;

(defmacro define-mod-operations (divisor)
  `(progn
     (defun mod* (&rest args)
       (reduce (lambda (x y) (mod (* x y) ,divisor)) args))

     (sb-c:define-source-transform mod* (&rest args)
       (if (null args)
           1
           (reduce (lambda (x y) `(mod (* ,x ,y) ,',divisor)) args)))

     (defun mod+ (&rest args)
       (reduce (lambda (x y) (mod (+ x y) ,divisor)) args))

     (sb-c:define-source-transform mod+ (&rest args)
       (if (null args)
           0
           (reduce (lambda (x y) `(mod (+ ,x ,y) ,',divisor)) args)))

     (defun mod- (&rest args)
       (reduce (lambda (x y) (mod (+ x y) ,divisor)) args))

     (sb-c:define-source-transform mod- (&rest args)
       (if (null args)
           0
           (reduce (lambda (x y) `(mod (- ,x ,y) ,',divisor)) args)))

     (define-modify-macro incfmod (delta)
       (lambda (x y) (mod (+ x y) ,divisor)))

     (define-modify-macro decfmod (delta)
       (lambda (x y) (mod (- x y) ,divisor)))

     (define-modify-macro mulfmod (multiplier)
       (lambda (x y) (mod (* x y) ,divisor)))))

(declaim (inline divisor-transform!))
(defun divisor-transform! (vector &optional (plus #'+))
  "Sets each VECTOR[i] to the sum of VECTOR[d] for all the divisors d of i."
  (declare (vector vector))
  (let ((n (length vector)))
    (loop for i from (- (ceiling n 2) 1) downto 1
          do (loop for j from (+ i i) below n by i
                   do (setf (aref vector j)
                            (funcall plus (aref vector j) (aref vector i)))))
    vector))

(declaim (inline inverse-divisor-transform!))
(defun inverse-divisor-transform! (vector &optional (minus #'-))
  "Does the inverse transform of DIVISOR-TRANSFORM!."
  (declare (vector vector))
  (let ((n (length vector)))
    (loop for i from 1 below (ceiling n 2)
          do (loop for j from (+ i i) below n by i
                   do (setf (aref vector j)
                            (funcall minus (aref vector j) (aref vector i)))))
    vector))

(declaim (inline multiple-transform!))
(defun multiple-transform! (vector &optional (plus #'+))
  "Sets each VECTOR[i] to the sum of VECTOR[m] for all the multiples m of i. (To
be precise, all the multiples smaller than the length of VECTOR.)"
  (declare (vector vector))
  (let ((n (length vector)))
    (loop for i from 1 below (ceiling n 2)
          do (loop for j from (+ i i) below n by i
                   do (setf (aref vector i)
                            (funcall plus (aref vector i) (aref vector j)))))
    vector))

(declaim (inline inverse-multiple-transform!))
(defun inverse-multiple-transform! (vector &optional (minus #'-))
  "Does the inverse transform of MULTIPLE-TRANSFORM!."
  (declare (vector vector))
  (let ((n (length vector)))
    (loop for i from (- (ceiling n 2) 1) downto 1
          do (loop for j from (+ i i) below n by i
                   do (setf (aref vector i)
                            (funcall minus (aref vector i) (aref vector j)))))
    vector))

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

;;;
;;; Body
;;;

(define-mod-operations +mod+)

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (as (make-array n :element-type 'uint31))
         (dp (make-array 1000001 :element-type 'uint31 :initial-element 0)))
    (declare (uint31 n))
    (dotimes (i n)
      (let ((a (read-fixnum)))
        (incfmod (aref dp a) a)
        (setf (aref as i) a)))
    (multiple-transform! dp #'mod+)
    (dotimes (i (length dp))
      (setf (aref dp i) (mod* (aref dp i) (aref dp i))))
    (inverse-multiple-transform! dp
                                 (lambda (x y)
                                   (let ((res (+ x (- +mod+ y))))
                                     (if (>= res +mod+)
                                         (- res +mod+)
                                         res))))
    (loop for a across as
          do (decfmod (aref dp a) (* a a)))
    (loop for i from 1 below (length dp)
          do (setf (aref dp i)
                   (mod* (aref dp i) (aref *inv* i))))
    (println (mod* (mod (reduce #'+ dp) +mod+)
                   (aref *inv* 2)))))

#-swank (main)

Score : 700 points

Problem Statement

We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.

Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):

\sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)

Since the answer may be enormous, compute it modulo 998244353.

Constraints

1 \leq N \leq 200000

1 \leq A_i \leq 1000000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0\ A_1\ \cdots\ A_{N-1}

Output

Print the sum modulo 998244353.

Sample Input 1

3
2 4 6

Sample Output 1

22

\mathrm{lcm}(2,4)+\mathrm{lcm}(2,6)+\mathrm{lcm}(4,6)=4+6+12=22.

Sample Input 2

8
1 2 3 4 6 8 12 12

Sample Output 2

313

Sample Input 3

10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644

Sample Output 3

353891724


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Disjoint set by Union-Find algorithm
;;;

(defstruct (disjoint-set
            (:constructor make-disjoint-set
                (size &aux (data (make-array size :element-type 'fixnum :initial-element -1))))
            (:conc-name ds-))
  (data nil :type (simple-array fixnum (*))))

(declaim (ftype (function * (values (mod #.array-total-size-limit) &optional)) ds-root))
(defun ds-root (disjoint-set x)
  "Returns the root of X."
  (declare (optimize (speed 3))
           ((mod #.array-total-size-limit) x))
  (let ((data (ds-data disjoint-set)))
    (if (< (aref data x) 0)
        x
        (setf (aref data x)
              (ds-root disjoint-set (aref data x))))))

(declaim (inline ds-unite!))
(defun ds-unite! (disjoint-set x1 x2)
  "Destructively unites X1 and X2 and returns true iff X1 and X2 become
connected for the first time."
  (let ((root1 (ds-root disjoint-set x1))
        (root2 (ds-root disjoint-set x2)))
    (unless (= root1 root2)
      (let ((data (ds-data disjoint-set)))
        ;; ensure the size of root1 >= the size of root2
        (when (> (aref data root1) (aref data root2))
          (rotatef root1 root2))
        (incf (aref data root1) (aref data root2))
        (setf (aref data root2) root1)))))

(declaim (inline ds-connected-p))
(defun ds-connected-p (disjoint-set x1 x2)
  "Returns true iff X1 and X2 have the same root."
  (= (ds-root disjoint-set x1) (ds-root disjoint-set x2)))

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (m (read))
         (q (read))
         (as (make-array q :element-type 'uint31))
         (bs (make-array q :element-type 'uint31))
         (cs (make-array q :element-type 'uint31))
         (dset (make-disjoint-set n))
         (table (make-hash-table :test #'eq :size n)))
    (declare (uint31 n q)
             (uint62 m))
    (dotimes (i q)
      (let ((a (read-fixnum))
            (b (read-fixnum))
            (c (read-fixnum)))
        (setf (aref as i) a
              (aref bs i) b
              (aref cs i) c)
        (when (zerop c)
          (ds-unite! dset a b))))
    (dotimes (i n)
      (setf (gethash (ds-root dset i) table) t))
    (let ((k (hash-table-count table)))
      (declare (uint31 k))
      (write-line
       (cond ((= m (- n 1))
              (if (zerop (count 1 cs))
                  "Yes"
                  "No"))
             ((loop for i below q
                    for a = (aref as i)
                    for b = (aref bs i)
                    for c = (aref cs i)
                    thereis (and (= c 1)
                                 (ds-connected-p dset a b)))
              "No")
             ((<= m (+ n (floor (* k (- k 3)) 2)))
              "Yes")
             (t "No"))))))

#-swank (main)

Score : 700 points

Problem Statement

Snuke's mother gave Snuke an undirected graph consisting of N vertices numbered 0 to N-1 and M edges.
This graph was connected and contained no parallel edges or self-loops.

One day, Snuke broke this graph.
Fortunately, he remembered Q clues about the graph.
The i-th clue (0 \leq i \leq Q-1) is represented as integers A_i,B_i,C_i and means the following:

If C_i=0: there was exactly one simple path (a path that never visits the same vertex twice) from Vertex A_i to B_i.

If C_i=1: there were two or more simple paths from Vertex A_i to B_i.

Snuke is not sure if his memory is correct, and worried whether there is a graph that matches these Q clues.
Determine if there exists a graph that matches Snuke's memory.

Constraints

2 \leq N \leq 10^5

N-1 \leq M \leq N \times (N-1)/2

1 \leq Q \leq 10^5

0 \leq A_i,B_i \leq N-1

A_i \neq B_i

0 \leq C_i \leq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M Q
A_0 B_0 C_0
A_1 B_1 C_1
\vdots
A_{Q-1} B_{Q-1} C_{Q-1}

Output

If there exists a graph that matches Snuke's memory, print Yes; otherwise, print No.

Sample Input 1

5 5 3
0 1 0
1 2 1
2 3 0

Sample Output 1

Yes

For example, consider a graph with edges (0,1),(1,2),(1,4),(2,3),(2,4). This graph matches the clues.

Sample Input 2

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

Sample Output 2

No

Sample Input 3

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

Sample Output 3

No


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Disjoint set by Union-Find algorithm
;;;

(defstruct (disjoint-set
            (:constructor make-disjoint-set
                (size &aux (data (make-array size :element-type 'fixnum :initial-element -1))))
            (:conc-name ds-))
  (data nil :type (simple-array fixnum (*))))

(declaim (ftype (function * (values (mod #.array-total-size-limit) &optional)) ds-root))
(defun ds-root (disjoint-set x)
  "Returns the root of X."
  (declare (optimize (speed 3))
           ((mod #.array-total-size-limit) x))
  (let ((data (ds-data disjoint-set)))
    (if (< (aref data x) 0)
        x
        (setf (aref data x)
              (ds-root disjoint-set (aref data x))))))

(declaim (inline ds-unite!))
(defun ds-unite! (disjoint-set x1 x2)
  "Destructively unites X1 and X2 and returns true iff X1 and X2 become
connected for the first time."
  (let ((root1 (ds-root disjoint-set x1))
        (root2 (ds-root disjoint-set x2)))
    (unless (= root1 root2)
      (let ((data (ds-data disjoint-set)))
        ;; ensure the size of root1 >= the size of root2
        (when (> (aref data root1) (aref data root2))
          (rotatef root1 root2))
        (incf (aref data root1) (aref data root2))
        (setf (aref data root2) root1)))))

(declaim (inline ds-connected-p))
(defun ds-connected-p (disjoint-set x1 x2)
  "Returns true iff X1 and X2 have the same root."
  (= (ds-root disjoint-set x1) (ds-root disjoint-set x2)))

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (m (read))
         (q (read))
         (as (make-array q :element-type 'uint31))
         (bs (make-array q :element-type 'uint31))
         (cs (make-array q :element-type 'uint31))
         (dset (make-disjoint-set n))
         (table (make-hash-table :test #'eq :size n)))
    (declare (uint31 n q)
             (uint62 m))
    (dotimes (i q)
      (let ((a (read-fixnum))
            (b (read-fixnum))
            (c (read-fixnum)))
        (setf (aref as i) a
              (aref bs i) b
              (aref cs i) c)
        (when (zerop c)
          (ds-unite! dset b c))))
    (dotimes (i n)
      (setf (gethash (ds-root dset i) table) t))
    (let ((k (hash-table-count table)))
      (declare (uint31 k))
      (write-line
       (cond ((= m (- n 1))
              (if (zerop (count 1 cs))
                  "Yes"
                  "No"))
             ((loop for i below q
                    for a = (aref as i)
                    for b = (aref bs i)
                    for c = (aref cs i)
                    thereis (and (= c 1)
                                 (ds-connected-p dset a b)))
              "No")
             (;; N-k+k <= M <= N-k + 1/2k(k-1)
              (<= m (+ n (floor (* k (- k 3)) 2)))
              "Yes")
             (t (error "Huh?");; "No"
                ))))))

#-swank (main)


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) (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
;;;
;;; Disjoint set by Union-Find algorithm
;;;

(defstruct (disjoint-set
            (:constructor make-disjoint-set
                (size &aux (data (make-array size :element-type 'fixnum :initial-element -1))))
            (:conc-name ds-))
  (data nil :type (simple-array fixnum (*))))

(declaim (ftype (function * (values (mod #.array-total-size-limit) &optional)) ds-root))
(defun ds-root (disjoint-set x)
  "Returns the root of X."
  (declare (optimize (speed 3))
           ((mod #.array-total-size-limit) x))
  (let ((data (ds-data disjoint-set)))
    (if (< (aref data x) 0)
        x
        (setf (aref data x)
              (ds-root disjoint-set (aref data x))))))

(declaim (inline ds-unite!))
(defun ds-unite! (disjoint-set x1 x2)
  "Destructively unites X1 and X2 and returns true iff X1 and X2 become
connected for the first time."
  (let ((root1 (ds-root disjoint-set x1))
        (root2 (ds-root disjoint-set x2)))
    (unless (= root1 root2)
      (let ((data (ds-data disjoint-set)))
        ;; ensure the size of root1 >= the size of root2
        (when (> (aref data root1) (aref data root2))
          (rotatef root1 root2))
        (incf (aref data root1) (aref data root2))
        (setf (aref data root2) root1)))))

(declaim (inline ds-connected-p))
(defun ds-connected-p (disjoint-set x1 x2)
  "Returns true iff X1 and X2 have the same root."
  (= (ds-root disjoint-set x1) (ds-root disjoint-set x2)))

(declaim (inline ds-size))
(defun ds-size (disjoint-set x)
  "Returns the size of the connected component to which X belongs."
  (- (aref (ds-data disjoint-set)
           (ds-root disjoint-set x))))

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (m (read))
         (q (read))
         (as (make-array q :element-type 'uint31))
         (bs (make-array q :element-type 'uint31))
         (cs (make-array q :element-type 'uint31))
         (dset (make-disjoint-set n))
         (table (make-hash-table :test #'eq :size n)))
    (declare (uint31 n q)
             (uint62 m))
    (dotimes (i q)
      (let ((a (read-fixnum))
            (b (read-fixnum))
            (c (read-fixnum)))
        (setf (aref as i) a
              (aref bs i) b
              (aref cs i) c)
        (when (zerop c)
          (ds-unite! dset b c))))
    (dotimes (i n)
      (setf (gethash (ds-root dset i) table) t))
    (let ((k (hash-table-count table)))
      (declare (uint31 k))
      (write-line
       (cond ((= m (- n 1))
              (if (zerop (count 1 cs))
                  "Yes"
                  "No"))
             ((loop for i below q
                    for a = (aref as i)
                    for b = (aref bs i)
                    for c = (aref cs i)
                    thereis (and (= c 1)
                                 (ds-connected-p dset a b)))
              "No")
             (;; N-k+k <= M <= N-k + 1/2k(k-1)
              (<= m (+ n (floor (* k (- k 3)) 2)))
              "Yes")
             (t "No"))))))

#-swank (main)


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) (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
;;;
;;; Disjoint set by Union-Find algorithm
;;;

(defstruct (disjoint-set
            (:constructor make-disjoint-set
                (size &aux (data (make-array size :element-type 'fixnum :initial-element -1))))
            (:conc-name ds-))
  (data nil :type (simple-array fixnum (*))))

(declaim (ftype (function * (values (mod #.array-total-size-limit) &optional)) ds-root))
(defun ds-root (x disjoint-set)
  "Returns the root of X."
  (declare (optimize (speed 3))
           ((mod #.array-total-size-limit) x))
  (let ((data (ds-data disjoint-set)))
    (if (< (aref data x) 0)
        x
        (setf (aref data x)
              (ds-root (aref data x) disjoint-set)))))

(declaim (inline ds-unite!))
(defun ds-unite! (x1 x2 disjoint-set)
  "Destructively unites X1 and X2 and returns true iff X1 and X2 become
connected for the first time."
  (let ((root1 (ds-root x1 disjoint-set))
        (root2 (ds-root x2 disjoint-set)))
    (unless (= root1 root2)
      (let ((data (ds-data disjoint-set)))
        ;; ensure the size of root1 >= the size of root2
        (when (> (aref data root1) (aref data root2))
          (rotatef root1 root2))
        (incf (aref data root1) (aref data root2))
        (setf (aref data root2) root1)))))

(declaim (inline ds-connected-p))
(defun ds-connected-p (x1 x2 disjoint-set)
  "Returns true iff X1 and X2 have the same root."
  (= (ds-root x1 disjoint-set) (ds-root x2 disjoint-set)))

(declaim (inline ds-size))
(defun ds-size (x disjoint-set)
  "Returns the size of the connected component to which X belongs."
  (- (aref (ds-data disjoint-set)
           (ds-root x disjoint-set))))

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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(declaim (inline =>))
(defun => (x y)
  (or (not x) y))

(defun main ()
  (let* ((n (read))
         (m (read))
         (q (read))
         (as (make-array q :element-type 'uint32))
         (bs (make-array q :element-type 'uint32))
         (cs (make-array q :element-type 'uint32))
         (dset (make-disjoint-set n))
         (table (make-hash-table :test #'eq :size n)))
    (declare (uint31 n m q))
    (dotimes (i q)
      (let ((a (read-fixnum ))
            (b (read-fixnum))
            (c (read-fixnum)))
        (setf (aref as i) a
              (aref bs i) b
              (aref cs i) c)
        (when (zerop c)
          (ds-unite! b c dset))))
    (dotimes (i n)
      (setf (gethash (ds-root i dset) table) t))
    (let ((k (hash-table-count table)))
      (declare (uint31 k))
      (write-line
       (cond ((= m (- n 1))
              (if (zerop (count 1 cs))
                  "Yes"
                  "No"))
             ((loop for i below q
                    for a = (aref as i)
                    for b = (aref bs i)
                    for c = (aref cs i)
                    thereis (and (= c 1)
                                 (ds-connected-p a b dset)))
              "No")
             (;; N-k+k <= M <= N-k + 1/2k(k-1)
              (<= m (+ n (floor (* k (- k 3)) 2)))
              "Yes")
             (t "No"))))))

#-swank (main)


(defun ans (w)
  (cond
    ((equal w "Sunny") "Cloudy")
    ((equal w "Cloudy") "Rainy")
    (t "Sunny")))

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

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


(defun f(s)
  (if (string= s "Sunny")
    "Cloudy"
    (if (string= s "Cloudy")
      "Rainy"
      "Sunny")))
(let ((line (read-line nil nil)))
  (format t "~A" (f line)))


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

;; BEGIN_INSERTED_CONTENTS
;; Should we do this with UNWIND-PROTECT?
(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
;;;

(defun main ()
  (declare #.OPT)
  (with-buffered-stdout
    (let* ((n (read))
           (k (read))
           (q (read))
           (dp (make-array n :element-type 'fixnum :initial-element (- k q))))
      (declare (uint62 n k q))
      (dotimes (i q)
        (let ((a (- (read-fixnum) 1)))
          (incf (aref dp a))))
      (dotimes (i n)
        (write-line
         (if (> (aref dp i) 0)
             "Yes"
             "No"))))))

#-swank (main)

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

10 13 15
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


(defun all-ok (n)
  (loop for i from 1 to n
        do (format t "Yes~%")))

(let ((n (read))
      (k (read))
      (q (read))
      (b 0)
      p)
  (setf b (- k q))
  (if (> b 0)
      (all-ok n)
      (progn
        (setf p (make-array n))
        (loop for i from 1 to q
              do (let ((a (read)))
                   (incf (aref p (1- a)))))
        (loop for o across p
              do (if (> (+ b o) 0)
                     (format t "Yes~%")
                     (format t "No~%"))))))


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) (read s nil nil 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 2 4 7 8 15 16 31 32 62 63 64)

;;;
;;; Bit-reversal operation
;;; Reference: https://stackoverflow.com/questions/746171/efficient-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c
;;;

(declaim ((simple-array (unsigned-byte 16) (65536)) *bit-reverse-table*))
(defparameter *bit-reverse-table*
  (make-array 65536 :element-type '(unsigned-byte 16)))

(defun initialize-bit-reverse-table ()
  (declare #.OPT)
  (let ((table *bit-reverse-table*))
    (dotimes (idx (length *bit-reverse-table*))
      (let ((x idx))
        (setq x (logior (ash (logand x #xaaaa) -1)
                        (ash (logand x #x5555) 1)))
        (setq x (logior (ash (logand x #xcccc) -2)
                        (ash (logand x #x3333) 2)))
        (setq x (logior (ash (logand x #xf0f0) -4)
                        (ash (logand x #x0f0f) 4)))
        (setq x (logior (ash x -8) (ldb (byte 16 0) (ash x 8))))
        (setf (aref table idx) x)))))

(initialize-bit-reverse-table)

(declaim (inline logreverse))
(defun logreverse (x size)
  "Returns the bit-reversal in the range [0, SIZE) of X."
  (declare ((unsigned-byte 64) x)
           ((integer 0 64) size))
  (let ((table *bit-reverse-table*))
    (ash (logior
          (ash (aref table (logand x #xffff)) 48)
          (ash (aref table (logand (ash x -16) #xffff)) 32)
          (ash (aref table (logand (ash x -32) #xffff)) 16)
          (aref table (logand (ash x -48) #xffff)))
         (- size 64))))

;;;
;;; Fast operations on GF(2)
;;;

(defun f2-echelon! (matrix)
  (declare #.OPT
           ((simple-array uint62 (100000)) matrix))
  (let* ((rank 0))
    (declare ((integer 0 #.most-positive-fixnum) rank))
    (dotimes (target-col 64)
      (let* ((pivot-row (do ((i rank (+ 1 i)))
                            ((= i 100000) -1)
                          (when (logbitp target-col (aref matrix i))
                            (return i)))))
        (when (>= pivot-row 0)
          ;; swap rows
          (rotatef (aref matrix rank) (aref matrix pivot-row))
          ;; eliminate the column
          (dotimes (i 100000)
            (when (and (/= i rank) (logbitp target-col (aref matrix i)))
              (setf (aref matrix i)
                    (logxor (aref matrix i)
                            (aref matrix rank)))))
          (incf rank))))
    (values matrix rank)))

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (as (make-array n :element-type 'uint62))
         (mat (sb-int:make-static-vector 100000 :element-type 'uint62)))
    (declare (uint32 n)
             ((simple-array uint62 (*)) mat))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)))
    (let* ((total-xor (reduce #'logxor as)))
      (declare (uint62 total-xor))
      (dotimes (i n)
        (setf (aref mat i)
              (logreverse (logandc2 (aref as i) total-xor) 62)))
      (f2-echelon! mat)
      (let ((rxor 0))
        (declare (uint62 rxor))
        (dotimes (i n)
          (setf rxor (logxor rxor (logreverse (aref mat i) 62))))
        (println (+ (logior rxor total-xor) rxor))))))

#-swank (main)

Score: 600 points

Problem Statement

We have N non-negative integers: A_1, A_2, ..., A_N.

Consider painting at least one and at most N-1 integers among them in red, and painting the rest in blue.

Let the beauty of the painting be the \mbox{XOR} of the integers painted in red, plus the \mbox{XOR} of the integers painted in blue.

Find the maximum possible beauty of the painting.

What is \mbox{XOR}?

The bitwise \mbox{XOR} x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows:

When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3 \oplus 5 = 6.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

0 \leq A_i < 2^{60}\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible beauty of the painting.

Sample Input 1

3
3 6 5

Sample Output 1

12

If we paint 3, 6, 5 in blue, red, blue, respectively, the beauty will be (6) + (3 \oplus 5) = 12.

There is no way to paint the integers resulting in greater beauty than 12, so the answer is 12.

Sample Input 2

4
23 36 66 65

Sample Output 2

188

Sample Input 3

20
1008288677408720767 539403903321871999 1044301017184589821 215886900497862655 504277496111605629 972104334925272829 792625803473366909 972333547668684797 467386965442856573 755861732751878143 1151846447448561405 467257771752201853 683930041385277311 432010719984459389 319104378117934975 611451291444233983 647509226592964607 251832107792119421 827811265410084479 864032478037725181

Sample Output 3

2012721721873704572

A_i and the answer may not fit into a 32-bit integer type.


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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; 1-dimensional binary indexed tree on arbitrary commutative monoid
;;;

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defconstant +time-limit+ 1.8f0)

(defun main ()
  (declare #.OPT
           (inline sort))
  (let* ((n (read))
         (as (make-array n :element-type 'uint62)))
    (declare (uint32 n))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)))
    (setf as (sort as #'>))
    (let ((rxor 0)
          (totalxor (reduce #'logxor as))
          (max-temp (float (the uint62 (sb-int:power-of-two-ceiling (reduce #'max as))) 1f0)))
      (declare (uint62 rxor totalxor)
               (single-float max-temp))
      (dotimes (i n)
        (when (evenp i)
          (setq rxor (logxor rxor (aref as i)))))
      (let ((res (+ rxor (logxor totalxor rxor))))
        (declare (uint62 res))
        (sb-int:with-progressive-timeout (get-remaining-time :seconds +time-limit+)
          (dotimes (_ most-positive-fixnum)
            (let ((remaining-time (get-remaining-time)))
              (when (eq 0 (get-remaining-time))
                (println res)
                (return-from main))
              (let* ((ratio (* (the single-float remaining-time) #.(/ +time-limit+)))
                     (temp (+ 1f0 (* max-temp ratio))))
                (declare (single-float temp))
                (dotimes (_ 5000)
                  (let* ((idx (random n))
                         (old-val (+ rxor (logxor totalxor rxor)))
                         (new-rxor (logxor rxor (aref as idx)))
                         (new-val (+ new-rxor (logxor totalxor new-rxor)))
                         (prob (exp (/ (- new-val old-val) temp))))
                    (declare (uint62 old-val new-val)
                             (single-float prob))
                    (when (< (random 1f0) prob)
                      (setq res (max res new-val)
                            rxor new-rxor))))))))))))

#-swank (main)


;; -*- coding: utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
  (sb-int:defconstant-eqx OPT
    #+swank '(optimize (speed 3) (safety 2))
    #-swank '(optimize (speed 3) (safety 0) (debug 0))
    #'equal)
  #+swank (ql:quickload '(:cl-debug-print :fiveam) :silent t)
  #-swank (set-dispatch-macro-character
           #\# #\> (lambda (s c p) (declare (ignore c p)) (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
;;;
;;; 1-dimensional binary indexed tree on arbitrary commutative monoid
;;;

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

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

(PROGN
 (DEFUN BITREE-UPDATE! (BITREE INDEX DELTA)
   "Destructively increments the vector: vector[INDEX] = vector[INDEX] +
DELTA"
   (declare #.OPT
            ((simple-array uint32 (*)) bitree)
            (int32 delta))
   (LET ((LEN (LENGTH BITREE)))
     (DO ((I INDEX (LOGIOR I (+ I 1))))
         ((>= I LEN) BITREE)
       (DECLARE ((INTEGER 0 4611686018427387903) I))
       (SETF (AREF BITREE I) (FUNCALL #'+ (AREF BITREE I) DELTA)))))
 (DEFUN BITREE-BISECT-LEFT (BITREE VALUE)
   "Returns the smallest index that satisfies VECTOR[0]+ ... +
VECTOR[index] >= VALUE. Returns the length of VECTOR if VECTOR[0]+
... +VECTOR[length-1] < VALUE."
   (DECLARE #.OPT
            ((simple-array uint32 (*)) BITREE)
            (uint32 value))
   (IF (NOT (FUNCALL #'< 0 VALUE))
       0
       (LET ((LEN (LENGTH BITREE)) (INDEX+1 0) (CUMUL 0))
         (DECLARE ((INTEGER 0 4611686018427387903) INDEX+1)
                  (TYPE UINT32 CUMUL))
         (DO ((DELTA (ASH 1 (- (INTEGER-LENGTH LEN) 1)) (ASH DELTA -1)))
             ((ZEROP DELTA) INDEX+1)
           (DECLARE ((INTEGER 0 4611686018427387903) DELTA))
           (LET ((NEXT-INDEX (+ INDEX+1 DELTA -1)))
             (WHEN (< NEXT-INDEX LEN)
               (LET ((NEXT-CUMUL (FUNCALL #'+ CUMUL (AREF BITREE NEXT-INDEX))))
                 (DECLARE (TYPE UINT32 NEXT-CUMUL))
                 (WHEN (FUNCALL #'< NEXT-CUMUL VALUE)
                   (SETF CUMUL NEXT-CUMUL)
                   (INCF INDEX+1 DELTA))))))))))

(defconstant +time-limit+ 1.8d0)

(defun main ()
  (declare #.OPT)
  (let* ((n (read))
         (as (make-array n :element-type 'uint62)))
    (declare (uint32 n))
    (dotimes (i n)
      (setf (aref as i) (read-fixnum)))
    (let ((rxor (aref as 0))
          (bxor (aref as 1))
          (rcount 1)
          (bcount 1)
          (rdp (make-array 100000 :element-type 'uint32))
          (bdp (make-array 100000 :element-type 'uint32))
          (res 0)
          (max-temp (float (the uint62 (sb-int:power-of-two-ceiling (reduce #'max as))) 1d0)))
      (declare (uint62 rxor bxor res)
               (uint32 rcount bcount)
               (double-float max-temp))
      (bitree-update! rdp 0 1)
      (bitree-update! bdp 1 1)
      (loop for i from 2 below n
            do (if (>= (logxor rxor (aref as i))
                       (logxor bxor (aref as i)))
                   (progn
                     (bitree-update! rdp i 1)
                     (incf rcount)
                     (setq rxor (logxor rxor (aref as i))))
                   (progn
                     (bitree-update! bdp i 1)
                     (incf bcount)
                     (setq bxor (logxor bxor (aref as i))))))
      (sb-int:with-progressive-timeout (get-remaining-time :seconds +time-limit+)
        (dotimes (_ most-positive-fixnum)
          (let ((remaining-time (get-remaining-time)))
            (when (eq 0 (get-remaining-time))
              (println res)
              (return-from main))
            (let* ((ratio (* (the single-float remaining-time) #.(/ +time-limit+)))
                   (temp (+ 1d0 (* max-temp ratio))))
              (dotimes (_ 5000)
                (let ((r (random 3)))
                  (cond ((= 0 r)
                         (let* ((rpos (+ 1 (random rcount)))
                                (bpos (+ 1 (random bcount)))
                                (ridx (bitree-bisect-left rdp rpos))
                                (bidx (bitree-bisect-left bdp bpos))
                                (rval (aref as ridx))
                                (bval (aref as bidx))
                                (old-val (+ rxor bxor))
                                (new-rxor (logxor rxor rval bval))
                                (new-bxor (logxor bxor rval bval))
                                (new-val (+ new-rxor new-bxor))
                                (prob (exp (/ (- new-val old-val) temp))))
                           (when (< (random 1d0) prob)
                             (setq res (max res new-val))
                             (setq rxor new-rxor
                                   bxor new-bxor)
                             (bitree-update! rdp ridx -1)
                             (bitree-update! bdp bidx -1)
                             (bitree-update! rdp bidx 1)
                             (bitree-update! bdp ridx 1))))
                        ((= 1 r)
                         (when (> rcount 1)
                           (let* ((rpos (+ 1 (random rcount)))
                                  (ridx (bitree-bisect-left rdp rpos))
                                  (rval (aref as ridx))
                                  (old-val (+ rxor bxor))
                                  (new-rxor (logxor rxor rval))
                                  (new-bxor (logxor bxor rval))
                                  (new-val (+ new-rxor new-bxor))
                                  (prob (exp (/ (- new-val old-val) temp))))
                             (declare (uint32 ridx))
                             (when (< (random 1d0) prob)
                               (setq res (max res new-val))
                               (decf rcount)
                               (incf bcount)
                               (setq rxor new-rxor
                                     bxor new-bxor)
                               (bitree-update! rdp ridx -1)
                               (bitree-update! bdp ridx 1)))))
                        (t
                         (when (> bcount 1)
                           (let* ((bpos (+ 1 (random bcount)))
                                  (bidx (bitree-bisect-left bdp bpos))
                                  (bval (aref as bidx))
                                  (old-val (+ rxor bxor))
                                  (new-rxor (logxor rxor bval))
                                  (new-bxor (logxor bxor bval))
                                  (new-val (+ new-rxor new-bxor))
                                  (prob (exp (/ (- new-val old-val) temp))))
                             (declare (uint32 bidx))
                             (when (< (random 1d0) prob)
                               (setq res (max res new-val))
                               (decf bcount)
                               (incf rcount)
                               (setq rxor new-rxor
                                     bxor new-bxor)
                               (bitree-update! bdp bidx -1)
                               (bitree-update! rdp bidx 1)))))))))))))))

#-swank (main)


Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


(defun main ()
  (let ((n (read)))
    (format t "~A~%" (expt n 3))))

(main)


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

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

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

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

(defconstant +mod+ 1000000007)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (bs (make-array (- n 1) :element-type 'uint32)))
    (dotimes (i (- n 1))
      (setf (aref bs i) (read)))
    (let ((as (make-array n :element-type 'uint32)))
      (setf (aref as 0) (aref bs 0))
      (setf (aref as (- n 1)) (aref bs (- n 2)))
      (loop for i from 1 below (- n 1)
            do (setf (aref as i)
                     (min (aref bs (- i 1)) (aref bs i))))
      (println (reduce #'+ as)))))

#-swank (main)

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

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

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    (run-program "C:/msys64/usr/bin/cat.exe" '("/dev/clipboard") :output out)))

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

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

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

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

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
2 5
"
    "9
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "2
3
"
    "6
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
0 153 10 10 23
"
    "53
")))

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


(defun count-happy-people (s)
  (labels ((inner (s &optional (cnt 0))
             (cond
               ((null (cdr s)) cnt)
               ((char-equal
                 (first s)
                 (second s))
                (inner (rest s) (1+ cnt)))
               (t
                (inner (rest s) cnt)))))
    (inner s)))

(defun solve (n k s)
  (let ((start (count-happy-people s)))
    (min (+ start (* k 2))
         (1- n))))

(defun main ()
  (let* ((n (read))
         (k (read))
         (s (concatenate 'list (read-line))))
    (format t "~a~%" (solve n k s))))

(main)

Score : 400 points

Problem Statement

There are N people standing in a queue from west to east.

Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between 0 and K (inclusive):

Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

|S| = N

Each character of S is L or R.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of happy people after at most K operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7