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

;;;
;;; Implicit treap
;;; (treap with implicit key)
;;;

;; Note:
;; - An empty treap is NIL.

(declaim (inline op))
(defun op (a b)
  "Is a binary operator comprising a monoid."
  (declare (uint62 a b))
  (min a b))

(defconstant +op-identity+ most-positive-fixnum
  "identity element w.r.t. OP")

(defstruct (itreap (:constructor %make-itreap (value priority &key left right (count 1) (accumulator value)))
                  (:copier nil)
                  (:conc-name %itreap-))
  (value +op-identity+ :type fixnum)
  (accumulator +op-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)
  "Returns the number of the elements."
  (declare ((or null itreap) itreap))
  (if itreap
      (%itreap-count itreap)
      0))

(declaim (inline itreap-accumulator))
(defun itreap-accumulator (itreap)
  "Returns the sum (w.r.t. OP) of the whole ITREAP:
ITREAP[0]+ITREAP[1]+...+ITREAP[SIZE-1]."
  (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))))
                  (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-up))
(defun force-up (itreap)
  "Propagates up the information from children."
  (declare (itreap itreap))
  (update-count itreap)
  (update-accumulator itreap))

(defun %heapify (top)
  "Properly swaps the priorities of the node and its two children."
  (declare (optimize (speed 3) (safety 0)))
  (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)))))

(declaim (inline make-itreap))
(defun make-itreap (size &key initial-contents)
  "Makes a treap of SIZE in O(SIZE) time. Its values are filled with the
identity element unless INITIAL-CONTENTS are supplied."
  (declare ((or null vector) initial-contents))
  (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 (if initial-contents
                                                (aref initial-contents mid)
                                                +op-identity+)
                                           (random most-positive-fixnum))))
                   (setf (%itreap-left node) (build l mid))
                   (setf (%itreap-right node) (build (+ mid 1) r))
                   (%heapify node)
                   (force-up node)
                   node))))
    (build 0 size)))

(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 (optimize (speed 3))
           ((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)))
             (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-up itreap)
                     (values left itreap))
                   (multiple-value-bind (left right)
                       (itreap-split (%itreap-right itreap) (- ikey left-count 1))
                     (setf (%itreap-right itreap) left)
                     (force-up itreap)
                     (values itreap right))))))
    (recur itreap index)))

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

(declaim (inline itreap-map))
(defun itreap-map (function itreap)
  "Successively applies FUNCTION to ITREAP[0], ..., ITREAP[SIZE-1]."
  (declare (function function))
  (labels ((recur (node)
             (when node
               (recur (%itreap-left node))
               (funcall function (%itreap-value node))
               (recur (%itreap-right node))
               (force-up node))))
    (recur itreap)))

(defmethod print-object ((object itreap) stream)
  (print-unreadable-object (object stream :type t)
    (let ((init t))
      (itreap-map (lambda (x)
                    (if init
                        (setq init nil)
                        (write-char #\  stream))
                   (write x :stream stream))
                 object))))

(declaim (inline itreap-ref))
(defun itreap-ref (itreap index)
  "Returns the element ITREAP[INDEX]."
  (declare ((integer 0 #.most-positive-fixnum) index))
  (unless (< index (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index index))
  (labels ((%ref (itreap index)
             (declare ((integer 0 #.most-positive-fixnum) index))
             (prog1
                 (let ((left-count (itreap-count (%itreap-left itreap))))
                   (cond ((< index left-count)
                          (%ref (%itreap-left itreap) index))
                         ((> index left-count)
                          (%ref (%itreap-right itreap) (- index left-count 1)))
                         (t (%itreap-value itreap))))
               (force-up itreap))))
    (%ref itreap index)))

(declaim (inline (setf itreap-ref)))
(defun (setf itreap-ref) (new-value itreap index)
  "Sets ITREAP[INDEX] to the given value."
  (declare ((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))
             (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-up itreap))))
    (%set itreap index)
    new-value))

(declaim (inline itreap-query))
(defun itreap-query (itreap l r)
  "Queries the `sum' (w.r.t. OP) of the range ITREAP[L, R)."
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (unless (<= l r (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index (cons l r)))
  (labels
      ((recur (itreap l r)
         (declare ((integer 0 #.most-positive-fixnum) l r))
         (unless itreap
           (return-from recur +op-identity+))
         (prog1
             (if (and (zerop l) (= r (%itreap-count itreap)))
                 (itreap-accumulator itreap)
                 (let ((left-count (itreap-count (%itreap-left itreap))))
                   (if (<= l left-count)
                       (if (< left-count r)
                           ;; LEFT-COUNT is in [L, R)
                           (op (op (recur (%itreap-left itreap) l (min r left-count))
                                   (%itreap-value itreap))
                               (recur (%itreap-right itreap) 0 (- r left-count 1)))
                           ;; LEFT-COUNT is in [R, END)
                           (recur (%itreap-left itreap) l (min r left-count)))
                       ;; LEFT-COUNT is in [0, L)
                       (recur (%itreap-right itreap) (- l left-count 1) (- r left-count 1)))))
           (force-up itreap))))
    (recur itreap l r)))

;; FIXME: might be problematic when two priorities collide and START is not
;; zero. (It will be negligible from the viewpoint of probability, however.)
(declaim (inline itreap-range-bisect-left))
(defun itreap-range-bisect-left (itreap value order &optional (start 0))
  "Returns the smallest index that satisfies ITREAP[START]+ ITREAP[START+1] +
... + ITREAP[index] >= VALUE (if ORDER is #'<).

Note:
- This function handles a **closed** interval.
- This function returns the length of ITREAP instead if ITREAP[START]+
... +ITREAP[length-1] < VALUE.
- The prefix sums of ITREAP, (ITREAP[START], ITREAP[START]+ITREAP[START+1], ...)
  must be monotone w.r.t. ORDER.
- ORDER must be a strict order"
  (declare ((integer 0 #.most-positive-fixnum) start))
  (multiple-value-bind (itreap-prefix itreap)
      (if (zerop start)
          (values nil itreap)
          (itreap-split itreap start))
    (labels
        ((recur (itreap offset prev-sum)
           (declare ((integer 0 #.most-positive-fixnum) offset)
                    #+sbcl (values (integer 0 #.most-positive-fixnum)))
           (unless itreap
             (return-from recur offset))
           (let ((sum prev-sum))
             (prog1
                 (cond ((not (funcall order
                                      (setq sum (op sum (itreap-accumulator (%itreap-left itreap))))
                                      value))
                        (recur (%itreap-left itreap) offset prev-sum))
                       ((not (funcall order
                                      (setq sum (op sum (%itreap-value itreap)))
                                      value))
                        (+ offset (itreap-count (%itreap-left itreap))))
                       (t
                        (recur (%itreap-right itreap)
                               (+ offset (itreap-count (%itreap-left itreap)) 1)
                               sum)))
               (force-up itreap)))))
      (prog1 (+ start (recur itreap 0 +op-identity+))
        (itreap-merge itreap-prefix itreap)))))

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

(declaim (inline delete-adjacent-duplicates))
(defun delete-adjacent-duplicates (seq &key (test #'eql))
  "Destructively deletes adjacent duplicates of SEQ: e.g. #(1 1 1 2 2 1 3) ->
#(1 2 1 3)"
  (declare (sequence seq)
           (function test))
  (etypecase seq
    (vector
     (if (zerop (length seq))
         seq
         (let ((prev (aref seq 0))
               (end 1))
           (loop for pos from 1 below (length seq)
                 unless (funcall test prev (aref seq pos))
                 do (setf prev (aref seq pos)
                          (aref seq end) (aref seq pos)
                          end (+ 1 end)))
           ;; KLUDGE: Resorting to ADJUST-ARRAY is maybe substandard.
           (if (array-has-fill-pointer-p seq)
               (adjust-array seq end :fill-pointer end)
               (adjust-array seq end)))))
    (list
     (loop for rest on seq
           unless (and (cdr rest)
                       (funcall test (first rest) (second rest)))
           collect (car rest)))))

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

;; Note:
;; - An empty treap is NIL.

(declaim (inline mop))
(defun mop (a b)
  "Is a binary moperator comprising a monoid."
  (declare (uint62 a b))
  (max a b))

(defconstant +mop-identity+ 0
  "identity element w.r.t. MOP")

(defstruct (mitreap (:constructor %make-mitreap (value priority &key left right (count 1) (accumulator value)))
                  (:copier nil)
                  (:conc-name %mitreap-))
  (value +mop-identity+ :type fixnum)
  (accumulator +mop-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 mitreap))
  (right nil :type (or null mitreap)))

(declaim (inline mitreap-count))
(defun mitreap-count (mitreap)
  "Returns the number of the elements."
  (declare ((or null mitreap) mitreap))
  (if mitreap
      (%mitreap-count mitreap)
      0))

(declaim (inline mitreap-accumulator))
(defun mitreap-accumulator (mitreap)
  "Returns the sum (w.r.t. MOP) of the whole MITREAP:
MITREAP[0]+MITREAP[1]+...+MITREAP[SIZE-1]."
  (declare ((or null mitreap) mitreap))
  (if mitreap
      (%mitreap-accumulator mitreap)
      +mop-identity+))

(declaim (inline mupdate-count))
(defun mupdate-count (mitreap)
  (declare (mitreap mitreap))
  (setf (%mitreap-count mitreap)
        (+ 1
           (mitreap-count (%mitreap-left mitreap))
           (mitreap-count (%mitreap-right mitreap)))))

(declaim (inline mupdate-accumulator))
(defun mupdate-accumulator (mitreap)
  (declare (mitreap mitreap))
  (setf (%mitreap-accumulator mitreap)
        (if (%mitreap-left mitreap)
            (if (%mitreap-right mitreap)
                (let ((mid (mop (%mitreap-accumulator (%mitreap-left mitreap))
                               (%mitreap-value mitreap))))
                  (mop mid (%mitreap-accumulator (%mitreap-right mitreap))))
                (mop (%mitreap-accumulator (%mitreap-left mitreap))
                    (%mitreap-value mitreap)))
            (if (%mitreap-right mitreap)
                (mop (%mitreap-value mitreap)
                    (%mitreap-accumulator (%mitreap-right mitreap)))
                (%mitreap-value mitreap)))))

(declaim (inline mforce-up))
(defun mforce-up (mitreap)
  "Propagates up the information from children."
  (declare (mitreap mitreap))
  (mupdate-count mitreap)
  (mupdate-accumulator mitreap))

(defun %mheapify (top)
  "Properly swaps the priorities of the node and its two children."
  (declare (optimize (speed 3) (safety 0)))
  (when top
    (let ((high-priority-node top))
      (when (and (%mitreap-left top)
                 (> (%mitreap-priority (%mitreap-left top))
                    (%mitreap-priority high-priority-node)))
        (setq high-priority-node (%mitreap-left top)))
      (when (and (%mitreap-right top)
                 (> (%mitreap-priority (%mitreap-right top))
                    (%mitreap-priority high-priority-node)))
        (setq high-priority-node (%mitreap-right top)))
      (unless (eql high-priority-node top)
        (rotatef (%mitreap-priority high-priority-node)
                 (%mitreap-priority top))
        (%mheapify high-priority-node)))))

(declaim (inline make-mitreap))
(defun make-mitreap (size &key initial-contents)
  "Makes a treap of SIZE in O(SIZE) time. Its values are filled with the
identity element unless INITIAL-CONTENTS are supplied."
  (declare ((or null vector) initial-contents))
  (labels ((build (l r)
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (if (= l r)
                 nil
                 (let* ((mid (ash (+ l r) -1))
                        (node (%make-mitreap (if initial-contents
                                                (aref initial-contents mid)
                                                +mop-identity+)
                                           (random most-positive-fixnum))))
                   (setf (%mitreap-left node) (build l mid))
                   (setf (%mitreap-right node) (build (+ mid 1) r))
                   (%mheapify node)
                   (mforce-up node)
                   node))))
    (build 0 size)))

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

(defun mitreap-merge (left right)
  "Destructively concatenates two MITREAPs."
  (declare #.OPT
           ((or null mitreap) left right))
  (cond ((null left) (when right (mforce-up right)) right)
        ((null right) (when left (mforce-up left)) left)
        (t (if (> (%mitreap-priority left) (%mitreap-priority right))
               (progn
                 (setf (%mitreap-right left)
                       (mitreap-merge (%mitreap-right left) right))
                 (mforce-up left)
                 left)
               (progn
                 (setf (%mitreap-left right)
                       (mitreap-merge left (%mitreap-left right)))
                 (mforce-up right)
                 right)))))

(declaim (inline mitreap-map))
(defun mitreap-map (function mitreap)
  "Successively applies FUNCTION to MITREAP[0], ..., MITREAP[SIZE-1]."
  (declare (function function))
  (labels ((recur (node)
             (when node
               (recur (%mitreap-left node))
               (funcall function (%mitreap-value node))
               (recur (%mitreap-right node))
               (mforce-up node))))
    (recur mitreap)))

(defmethod print-object ((object mitreap) stream)
  (print-unreadable-object (object stream :type t)
    (let ((init t))
      (mitreap-map (lambda (x)
                    (if init
                        (setq init nil)
                        (write-char #\  stream))
                   (write x :stream stream))
                 object))))

(declaim (inline mitreap-ref))
(defun mitreap-ref (mitreap index)
  "Returns the element MITREAP[INDEX]."
  (declare ((integer 0 #.most-positive-fixnum) index))
  (unless (< index (mitreap-count mitreap))
    (error 'invalid-mitreap-index-error :mitreap mitreap :index index))
  (labels ((%ref (mitreap index)
             (declare ((integer 0 #.most-positive-fixnum) index))
             (prog1
                 (let ((left-count (mitreap-count (%mitreap-left mitreap))))
                   (cond ((< index left-count)
                          (%ref (%mitreap-left mitreap) index))
                         ((> index left-count)
                          (%ref (%mitreap-right mitreap) (- index left-count 1)))
                         (t (%mitreap-value mitreap))))
               (mforce-up mitreap))))
    (%ref mitreap index)))

(declaim (inline (setf mitreap-ref)))
(defun (setf mitreap-ref) (new-value mitreap index)
  "Sets MITREAP[INDEX] to the given value."
  (declare ((integer 0 #.most-positive-fixnum) index))
  (unless (< index (mitreap-count mitreap))
    (error 'invalid-mitreap-index-error :mitreap mitreap :index index))
  (labels ((%set (mitreap index)
             (declare ((integer 0 #.most-positive-fixnum) index))
             (prog1
                 (let ((left-count (mitreap-count (%mitreap-left mitreap))))
                   (cond ((< index left-count)
                          (%set (%mitreap-left mitreap) index))
                         ((> index left-count)
                          (%set (%mitreap-right mitreap) (- index left-count 1)))
                         (t (setf (%mitreap-value mitreap) new-value))))
               (mforce-up mitreap))))
    (%set mitreap index)
    new-value))

(declaim (inline mitreap-query))
(defun mitreap-query (mitreap l r)
  "Queries the `sum' (w.r.t. MOP) of the range MITREAP[L, R)."
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (unless (<= l r (mitreap-count mitreap))
    (error 'invalid-mitreap-index-error :mitreap mitreap :index (cons l r)))
  (labels
      ((recur (mitreap l r)
         (declare ((integer 0 #.most-positive-fixnum) l r))
         (unless mitreap
           (return-from recur +mop-identity+))
         (prog1
             (if (and (zerop l) (= r (%mitreap-count mitreap)))
                 (mitreap-accumulator mitreap)
                 (let ((left-count (mitreap-count (%mitreap-left mitreap))))
                   (if (<= l left-count)
                       (if (< left-count r)
                           ;; LEFT-COUNT is in [L, R)
                           (mop (mop (recur (%mitreap-left mitreap) l (min r left-count))
                                   (%mitreap-value mitreap))
                               (recur (%mitreap-right mitreap) 0 (- r left-count 1)))
                           ;; LEFT-COUNT is in [R, END)
                           (recur (%mitreap-left mitreap) l (min r left-count)))
                       ;; LEFT-COUNT is in [0, L)
                       (recur (%mitreap-right mitreap) (- l left-count 1) (- r left-count 1)))))
           (mforce-up mitreap))))
    (recur mitreap l r)))

;; FIXME: might be problematic when two priorities collide and START is not
;; zero. (It will be negligible from the viewpoint of probability, however.)
(declaim (inline mitreap-range-bisect-left))
(defun mitreap-range-bisect-left (mitreap value order &optional (start 0))
  "Returns the smallest index that satisfies MITREAP[START]+ MITREAP[START+1] +
... + MITREAP[index] >= VALUE (if ORDER is #'<).

Note:
- This function handles a **closed** interval.
- This function returns the length of MITREAP instead if MITREAP[START]+
... +MITREAP[length-1] < VALUE.
- The prefix sums of MITREAP, (MITREAP[START], MITREAP[START]+MITREAP[START+1], ...)
  must be monotone w.r.t. ORDER.
- ORDER must be a strict order"
  (declare ((integer 0 #.most-positive-fixnum) start))
  (multiple-value-bind (mitreap-prefix mitreap)
      (if (zerop start)
          (values nil mitreap)
          (mitreap-split mitreap start))
    (labels
        ((recur (mitreap offset prev-sum)
           (declare ((integer 0 #.most-positive-fixnum) offset)
                    #+sbcl (values (integer 0 #.most-positive-fixnum)))
           (unless mitreap
             (return-from recur offset))
           (let ((sum prev-sum))
             (prog1
                 (cond ((not (funcall order
                                      (setq sum (mop sum (mitreap-accumulator (%mitreap-left mitreap))))
                                      value))
                        (recur (%mitreap-left mitreap) offset prev-sum))
                       ((not (funcall order
                                      (setq sum (mop sum (%mitreap-value mitreap)))
                                      value))
                        (+ offset (mitreap-count (%mitreap-left mitreap))))
                       (t
                        (recur (%mitreap-right mitreap)
                               (+ offset (mitreap-count (%mitreap-left mitreap)) 1)
                               sum)))
               (mforce-up mitreap)))))
      (prog1 (+ start (recur mitreap 0 +mop-identity+))
        (mitreap-merge mitreap-prefix mitreap)))))

(defun main ()
  (let* ((n (read))
         (as (make-array n :element-type 'uint31))
         (bs (make-array n :element-type 'uint31))
         (pairs (make-array n :element-type '(cons uint32 uint32))))
    (dotimes (i n)
      (let ((a (read-fixnum)))
        (setf (aref as i) a)))
    (dotimes (i n)
      (let ((b (read-fixnum)))
        (setf (aref bs i) b)))
    (dotimes (i n)
      (setf (aref pairs i)
            (cons (aref as i) (aref bs i))))
    (setq pairs (sort pairs (lambda (x y) (< (the uint31 x) (the uint31 y))) :key #'cdr))
    (let ((new-as (make-array n :element-type 'uint31))
          (sorted-as (sort (copy-seq as) #'<))
          (sorted-bs (sort (copy-seq bs) #'<)))
      (declare ((simple-array uint31 (*)) sorted-as sorted-bs))
      (dotimes (i n)
        (setf (aref new-as i) (car (aref pairs i))))
      (when (loop for a across sorted-as
                  for b across sorted-bs
                  thereis (> a b))
        (write-line "No")
        (return-from main))
      (when (< (length (delete-adjacent-duplicates (copy-seq sorted-as)))
               n)
        (write-line "Yes")
        (return-from main))
      (let ((dp (make-itreap n :initial-contents new-as))
            (pos 0)
            (count 0))
        (loop (when (= count (- n 2))
                (return))
              ;; (loop while (and (< pos n)
              ;;                  (<= (itreap-ref dp pos) (aref sorted-bs pos)))
              ;;       do (incf pos))
              ;; (when (= pos n)
              ;;   (return))
              (let* ((new-min (itreap-query dp pos n))
                     (min-pos (itreap-range-bisect-left dp (aref sorted-bs pos) #'> pos)))
                (declare (uint62 new-min min-pos))
                (unless (= min-pos pos)
                  (rotatef (itreap-ref dp pos)
                           (itreap-ref dp min-pos))
                  (incf count))
                (incf pos)))
        (when (loop for i below n
                    always (<= (itreap-ref dp i) (aref sorted-bs i)))
          (write-line "Yes")
          (return-from main)))
      ;; (let ((dp (make-mitreap n :initial-contents new-as))
      ;;       (pos (- n 1)))
      ;;   (dotimes (i (- n 2))
      ;;     (loop while (and (<= 0 pos)
      ;;                      (<= (mitreap-ref dp pos) (aref sorted-bs pos)))
      ;;           do (decf pos))
      ;;     (when (< pos 0)
      ;;       (return))
      ;;     (let* ((new-max (mitreap-query dp 0 (+ pos 1)))
      ;;            (max-pos (mitreap-range-bisect-left dp new-max #'<)))
      ;;       (declare (uint62 new-max max-pos))
      ;;       (unless (<= new-max (mitreap-ref dp pos))
      ;;         (write-line "No")
      ;;         (return-from main))
      ;;       (rotatef (mitreap-ref dp pos)
      ;;                (mitreap-ref dp max-pos))))
      ;;   (when (loop for i below n
      ;;               always (<= (mitreap-ref dp i) (aref sorted-bs i)))
      ;;     (write-line "Yes")
      ;;     (return-from main)))
      (write-line "No"))))

#-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
1 3 2
1 2 3
"
    "Yes
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 2 3
2 2 2
"
    "No
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
3 1 2 6 3 4
2 2 8 3 4 3
"
    "Yes
")))

Score : 600 points

Problem Statement

Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N.
Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:

Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y.

Constraints

2 \leq N \leq 10^5

1 \leq A_i,B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

3
1 3 2
1 2 3

Sample Output 1

Yes

We should swap the values of A_2 and A_3.

Sample Input 2

3
1 2 3
2 2 2

Sample Output 2

No

Sample Input 3

6
3 1 2 6 3 4
2 2 8 3 4 3

Sample Output 3

Yes


;; -*- 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 (inline delete-adjacent-duplicates))
(defun delete-adjacent-duplicates (seq &key (test #'eql))
  "Destructively deletes adjacent duplicates of SEQ: e.g. #(1 1 1 2 2 1 3) ->
#(1 2 1 3)"
  (declare (sequence seq)
           (function test))
  (etypecase seq
    (vector
     (if (zerop (length seq))
         seq
         (let ((prev (aref seq 0))
               (end 1))
           (loop for pos from 1 below (length seq)
                 unless (funcall test prev (aref seq pos))
                 do (setf prev (aref seq pos)
                          (aref seq end) (aref seq pos)
                          end (+ 1 end)))
           ;; KLUDGE: Resorting to ADJUST-ARRAY is maybe substandard.
           (if (array-has-fill-pointer-p seq)
               (adjust-array seq end :fill-pointer end)
               (adjust-array seq end)))))
    (list
     (loop for rest on seq
           unless (and (cdr rest)
                       (funcall test (first rest) (second rest)))
           collect (car rest)))))

(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))
         (as (make-array n :element-type 'uint31))
         (bs (make-array n :element-type 'uint31)))
    (dotimes (i n)
      (let ((a (read-fixnum)))
        (setf (aref as i) a)))
    (dotimes (i n)
      (let ((b (read-fixnum)))
        (setf (aref bs i) b)))
    (let ((sorted-as (sort (copy-seq as) #'<))
          (sorted-bs (sort (copy-seq bs) #'<)))
      (when (loop for a across sorted-as
                  for b across sorted-bs
                  thereis (> a b))
        (write-line "No")
        (return-from main))
      #>as
      (when (< (length (delete-adjacent-duplicates (copy-seq sorted-as)))
               n)
        (write-line "Yes")
        (return-from main))
      (error "Huh?"))))

#-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
1 3 2
1 2 3
"
    "Yes
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "3
1 2 3
2 2 2
"
    "No
"))
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "6
3 1 2 6 3 4
2 2 8 3 4 3
"
    "Yes
")))

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.


(in-package :cl-user)
(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 (set-dispatch-macro-character #\# #\> #'cl-debug-print:debug-print-reader)

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

(defconstant +mod+ 1000000007)

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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Implicit treap
;;; (treap with implicit key)
;;;

;; TODO: abstraction

(defpackage :cp/implicit-treap
  (:use :cl)
  (:export #:itreap #:itreap-p #:itreap-count #:itreap-accumulator
           #:make-itreap #:invalid-itreap-index-error #:itreap-ref
           #:itreap-split #:itreap-merge #:itreap-insert #:itreap-delete
           #:itreap-push #:itreap-pop #:itreap-map #:do-itreap
           #:itreap-fold #:itreap-fold-bisect #:itreap-fold-bisect-from-end
           #:itreap-update #:itreap-reverse
           #:itreap-bisect-left #:itreap-bisect-right #:itreap-insort))
(in-package :cp/implicit-treap)

;; Note:
;; - An empty treap is NIL.

(declaim (inline op))
(defun op (a b)
  "Is a binary operator comprising a monoid."
  (min a b))

(defconstant +op-identity+ most-positive-fixnum
  "identity element w.r.t. OP")

(declaim (inline updater-op))
(defun updater-op (lazy x)
  "Is the operator to compute and update LAZY value. LAZY is the current LAZY
value and X is an operand."
  (min lazy x))

(defconstant +updater-identity+ most-positive-fixnum
  "identity element w.r.t. UPDATER-OP")

(declaim (inline modifier-op))
(defun modifier-op (acc lazy size)
  "Is the operator to update ACCUMULATOR (and VALUE) based on LAZY value. ACC is
the current ACCUMULATOR value and LAZY is the LAZY value. SIZE is the length of
the target interval."
  (declare (ignorable size))
  (min acc lazy))

(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 fixnum)
  (accumulator +op-identity+ :type fixnum)
  (lazy +updater-identity+ :type fixnum)
  (priority 0 :type (integer 0 #.most-positive-fixnum))
  (count 1 :type (mod #.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)
  "Returns the number of the elements of ITREAP."
  (declare ((or null itreap) itreap))
  (if itreap
      (%itreap-count itreap)
      0))

(declaim (inline itreap-accumulator))
(defun itreap-accumulator (itreap)
  "Returns the sum (w.r.t. OP) of the whole ITREAP:
ITREAP[0]+ITREAP[1]+...+ITREAP[SIZE-1]."
  (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))))
                  (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-up))
(defun force-up (itreap)
  "Propagates up the information from children."
  (declare (itreap itreap))
  (update-count itreap)
  (update-accumulator itreap))

(declaim (inline force-down))
(defun force-down (itreap)
  "Propagates down the information to children."
  (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 %heapify (node)
  "Makes it max-heap w.r.t. priorities by swapping the priorities of the whole
treap."
  (declare (optimize (speed 3) (safety 0)))
  (when node
    (let ((high-priority-node node))
      (when (and (%itreap-left node)
                 (> (%itreap-priority (%itreap-left node))
                    (%itreap-priority high-priority-node)))
        (setq high-priority-node (%itreap-left node)))
      (when (and (%itreap-right node)
                 (> (%itreap-priority (%itreap-right node))
                    (%itreap-priority high-priority-node)))
        (setq high-priority-node (%itreap-right node)))
      (unless (eql high-priority-node node)
        (rotatef (%itreap-priority high-priority-node)
                 (%itreap-priority node))
        (%heapify high-priority-node)))))

(declaim (inline make-itreap))
(defun make-itreap (size &key initial-contents)
  "Makes a treap of SIZE in O(SIZE) time. Its values are filled with the
identity element unless INITIAL-CONTENTS are supplied."
  (declare ((or null vector) initial-contents))
  (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 (if initial-contents
                                                (aref initial-contents mid)
                                                +op-identity+)
                                            (random most-positive-fixnum))))
                   (setf (%itreap-left node) (build l mid))
                   (setf (%itreap-right node) (build (+ mid 1) r))
                   (%heapify node)
                   (force-up node)
                   node))))
    (build 0 size)))

(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 itreap-split (itreap index)
  "Destructively splits ITREAP at INDEX and returns two treaps (in ascending
order)."
  (declare (optimize (speed 3))
           ((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-up itreap)
                     (values left itreap))
                   (multiple-value-bind (left right)
                       (itreap-split (%itreap-right itreap) (- ikey left-count 1))
                     (setf (%itreap-right itreap) left)
                     (force-up itreap)
                     (values itreap right))))))
    (recur itreap index)))

(defun itreap-merge (left right)
  "Destructively concatenates two ITREAPs. Note that this `merge' is different
from CL:MERGE and rather close to CL:CONCATENATE."
  (declare (optimize (speed 3))
           ((or null itreap) left right))
  (cond ((null left) (when right (force-down right) (force-up right)) right)
        ((null right) (when left (force-down left) (force-up 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-up left)
                 left)
               (progn
                 (setf (%itreap-left right)
                       (itreap-merge left (%itreap-left right)))
                 (force-up right)
                 right)))))

(defun itreap-insert (itreap index obj)
  "Destructively inserts OBJ into ITREAP at INDEX and returns the resultant treap.

You cannot rely on the side effect. Use the returned value."
  (declare (optimize (speed 3))
           ((or null itreap) itreap)
           ((integer 0 #.most-positive-fixnum) index))
  (unless (<= index (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index index))
  (let ((node (%make-itreap obj (random most-positive-fixnum))))
    (labels ((recur (itreap ikey)
               (declare ((integer 0 #.most-positive-fixnum) ikey))
               (unless itreap (return-from recur node))
               (force-down itreap)
               (if (> (%itreap-priority node) (%itreap-priority itreap))
                   (progn
                     (setf (values (%itreap-left node) (%itreap-right node))
                           (itreap-split itreap ikey))
                     (force-up node)
                     node)
                   (let ((left-count (itreap-count (%itreap-left itreap))))
                     (if (<= ikey left-count)
                         (setf (%itreap-left itreap)
                               (recur (%itreap-left itreap) ikey))
                         (setf (%itreap-right itreap)
                               (recur (%itreap-right itreap) (- ikey left-count 1))))
                     (force-up itreap)
                     itreap))))
      (recur itreap index))))

(defun itreap-delete (itreap index)
  "Destructively deletes the object at INDEX in ITREAP.

You cannot rely on the side effect. Use the returned value."
  (declare (optimize (speed 3))
           ((integer 0 #.most-positive-fixnum) index))
  (unless (< index (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index index))
  (labels ((recur (itreap ikey)
             (declare ((integer 0 #.most-positive-fixnum) ikey))
             (force-down itreap)
             (let ((left-count (itreap-count (%itreap-left itreap))))
               (cond ((< ikey left-count)
                      (setf (%itreap-left itreap)
                            (recur (%itreap-left itreap) ikey))
                      (force-up itreap)
                      itreap)
                     ((> ikey left-count)
                      (setf (%itreap-right itreap)
                            (recur (%itreap-right itreap) (- ikey left-count 1)))
                      (force-up itreap)
                      itreap)
                     (t
                      (itreap-merge (%itreap-left itreap) (%itreap-right itreap)))))))
    (recur itreap index)))

(defmacro itreap-push (obj itreap pos)
  "Pushes OBJ to ITREAP at POS."
  `(setf ,itreap (itreap-insert ,itreap ,pos ,obj)))

(defmacro itreap-pop (itreap pos)
  "Returns the object at POS and deletes it."
  (let ((p (gensym)))
    `(let ((,p ,pos))
       (prog1 (itreap-ref ,itreap ,p)
         (setf ,itreap (itreap-delete ,itreap ,p))))))

(declaim (inline itreap-map))
(defun itreap-map (function itreap)
  "Successively applies FUNCTION to ITREAP[0], ..., ITREAP[SIZE-1]."
  (declare (function function))
  (labels ((recur (node)
             (when node
               (force-down node)
               (recur (%itreap-left node))
               (funcall function (%itreap-value node))
               (recur (%itreap-right node))
               (force-up node))))
    (recur itreap)))

(defmethod print-object ((object itreap) stream)
  (print-unreadable-object (object stream :type t)
    (let ((init t))
      (itreap-map (lambda (x)
                    (if init
                        (setq init nil)
                        (write-char #\  stream))
                    (write x :stream stream))
                  object))))

(defmacro do-itreap ((var itreap &optional result) &body body)
  "Successively binds ITREAP[0], ..., ITREAP[SIZE-1] to VAR and executes BODY
each time."
  `(block nil
     (itreap-map (lambda (,var) ,@body) ,itreap)
     ,result))

(defun itreap (&rest args)
  ;; NOTE: This function takes O(nlog(n)) time. Use MAKE-ITREAP for efficiency.
  (labels ((recur (list position itreap)
             (declare ((integer 0 #.most-positive-fixnum) position))
             (if (null list)
                 itreap
                 (recur (cdr list)
                        (1+ position)
                        (itreap-insert itreap position (car list))))))
    (recur args 0 nil)))

(declaim (inline itreap-ref))
(defun itreap-ref (itreap index)
  "Returns the element ITREAP[INDEX]."
  (declare ((integer 0 #.most-positive-fixnum) index))
  (unless (< index (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index index))
  (labels ((%ref (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)
                          (%ref (%itreap-left itreap) index))
                         ((> index left-count)
                          (%ref (%itreap-right itreap) (- index left-count 1)))
                         (t (%itreap-value itreap))))
               (force-up itreap))))
    (%ref itreap index)))

(declaim (inline (setf itreap-ref)))
(defun (setf itreap-ref) (new-value itreap index)
  "Sets ITREAP[INDEX] to the given value."
  (declare ((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-up itreap))))
    (%set itreap index)
    new-value))

(declaim (inline itreap-fold))
(defun itreap-fold (itreap l r)
  "Returns the `sum' (w.r.t. OP) of the range ITREAP[L, R)."
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (unless (<= l r (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index (cons l r)))
  (labels
      ((recur (itreap l r)
         (declare ((integer 0 #.most-positive-fixnum) l r))
         (unless itreap
           (return-from recur +op-identity+))
         (force-down itreap)
         (prog1
             (if (and (zerop l) (= r (%itreap-count itreap)))
                 (itreap-accumulator itreap)
                 (let ((left-count (itreap-count (%itreap-left itreap))))
                   (if (<= l left-count)
                       (if (< left-count r)
                           ;; LEFT-COUNT is in [L, R)
                           (op (op (recur (%itreap-left itreap) l (min r left-count))
                                   (%itreap-value itreap))
                               (recur (%itreap-right itreap) 0 (- r left-count 1)))
                           ;; LEFT-COUNT is in [R, END)
                           (recur (%itreap-left itreap) l (min r left-count)))
                       ;; LEFT-COUNT is in [0, L)
                       (recur (%itreap-right itreap) (- l left-count 1) (- r left-count 1)))))
           (force-up itreap))))
    (recur itreap l r)))

;; FIXME: might be problematic when two priorities collide and START is not
;; zero. (It will be negligible from the viewpoint of probability, however.)
(declaim (inline itreap-fold-bisect))
(defun itreap-fold-bisect (itreap test &optional (start 0))
  "Returns the largest index that satisfies (FUNCALL TEST (OP ITREAP[START]
ITREAP[START+1] ... ITREAP[index-1])).

Note:
- (FUNCALL TEST +OP-IDENTITY+) must be true.
- TEST must be monotone in the target range.
"
  (declare ((integer 0 #.most-positive-fixnum) start))
  (assert (funcall test +op-identity+))
  (multiple-value-bind (itreap-prefix itreap)
      (if (zerop start)
          (values nil itreap)
          (itreap-split itreap start))
    (labels
        ((recur (itreap offset prev-sum)
           (declare ((integer 0 #.most-positive-fixnum) offset)
                    #+sbcl (values (integer 0 #.most-positive-fixnum)))
           (unless itreap
             (return-from recur offset))
           (force-down itreap)
           (let ((sum prev-sum))
             (prog1
                 (cond ((not (funcall test (setq sum (op sum (itreap-accumulator (%itreap-left itreap))))))
                        (recur (%itreap-left itreap) offset prev-sum))
                       ((not (funcall test (setq sum (op sum (%itreap-value itreap)))))
                        (+ offset (itreap-count (%itreap-left itreap))))
                       (t
                        (recur (%itreap-right itreap)
                               (+ offset (itreap-count (%itreap-left itreap)) 1)
                               sum)))
               (force-up itreap)))))
      (prog1 (+ start (recur itreap 0 +op-identity+))
        (itreap-merge itreap-prefix itreap)))))

(declaim (inline itreap-fold-bisect-from-end))
(defun itreap-fold-bisect-from-end (itreap test &optional end)
  "Returns the smallest index that satisfies (FUNCALL TEST (OP ITREAP[index]
  ITREAP[index+1] ... ITREAP[END-1])).

Note:
- (FUNCALL TEST +OP-IDENTITY+) must be true.
- TEST must be monotone in the target range.
"
  (declare ((or null (integer 0 #.most-positive-fixnum)) end))
  (assert (funcall test +op-identity+))
  (multiple-value-bind (itreap itreap-suffix)
      (if end
          (itreap-split itreap end)
          (values itreap nil))
    (labels
        ((recur (itreap offset prev-sum)
           (declare ((integer 0 #.most-positive-fixnum) offset)
                    #+sbcl (values (integer 0 #.most-positive-fixnum)))
           (unless itreap
             (return-from recur offset))
           (force-down itreap)
           (let ((sum prev-sum))
             (prog1
                 (cond ((not (funcall test (setq sum (op (itreap-accumulator (%itreap-right itreap)) sum))))
                        (recur (%itreap-right itreap) offset prev-sum))
                       ((not (funcall test (setq sum (op (%itreap-value itreap) sum))))
                        (+ offset (itreap-count (%itreap-right itreap))))
                       (t
                        (recur (%itreap-left itreap)
                               (+ offset (itreap-count (%itreap-right itreap)) 1)
                               sum)))
               (force-up itreap)))))
      (prog1 (- (or end (itreap-count itreap))
                (recur itreap 0 +op-identity+))
        (itreap-merge itreap itreap-suffix)))))

(declaim (inline itreap-update))
(defun itreap-update (itreap operand l r)
  "Updates ITRAP by ITREAP[i] := (OP ITREAP[i] OPERAND) for all i in [l, r)"
  (declare ((integer 0 #.most-positive-fixnum) l r))
  (unless (<= l r (itreap-count itreap))
    (error 'invalid-itreap-index-error :itreap itreap :index (cons l r)))
  (labels
      ((recur (itreap l r)
         (declare ((integer 0 #.most-positive-fixnum) l r))
         (when itreap
           (if (and (zerop l) (= r (%itreap-count itreap)))
               (progn
                 (setf (%itreap-lazy itreap)
                       (updater-op (%itreap-lazy itreap) operand))
                 (force-down itreap))
               (let ((left-count (itreap-count (%itreap-left itreap))))
                 (force-down itreap)
                 (if (<= l left-count)
                     (if (< left-count r)
                         ;; LEFT-COUNT is in [L, R)
                         (progn
                           (recur (%itreap-left itreap) l (min r left-count))
                           (setf (%itreap-value itreap)
                                 (modifier-op (%itreap-value itreap) operand 1))
                           (recur (%itreap-right itreap) 0 (- r left-count 1)))
                         ;; LEFT-COUNT is in [R, END)
                         (recur (%itreap-left itreap) l (min r left-count)))
                     ;; LEFT-COUNT is in [0, L)
                     (recur (%itreap-right itreap) (- l left-count 1) (- r left-count 1)))))
           (force-up itreap))))
    (recur itreap l r)
    itreap))

;;;
;;; Below are utilities for treap whose values are sorted w.r.t. some order
;;;

(declaim (inline itreap-bisect-left)
         (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) itreap-bisect-left))
(defun itreap-bisect-left (itreap value order)
  "Takes a **sorted** treap and returns the smallest index that satisfies
ITREAP[index] >= VALUE, where >= is the complement of ORDER. In other words,
this function returns a leftmost index at which value can be inserted with
keeping the order. Returns the size of ITREAP if ITREAP[length-1] <
VALUE. The time complexity is O(log(n))."
  (labels ((recur (count itreap)
             (declare ((integer 0 #.most-positive-fixnum) count))
             (cond ((null itreap) nil)
                   ((funcall order (%itreap-value itreap) value)
                    (recur count (%itreap-right itreap)))
                   (t
                    (let ((left-count (- count (itreap-count (%itreap-right itreap)) 1)))
                      (or (recur left-count (%itreap-left itreap))
                          left-count))))))
    (or (recur (itreap-count itreap) itreap)
        (itreap-count itreap))))

(declaim (inline itreap-bisect-right)
         (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) itreap-bisect-right))
(defun itreap-bisect-right (itreap value order)
  "Takes a **sorted** treap and returns the smallest index that satisfies
VALUE < ITREAP[index], where < is ORDER. In other words, this function
returns a rightmost index at which VALUE can be inserted with keeping the
order. Returns the size of ITREAP if ITREAP[length-1] <= VALUE. The time
complexity is O(log(n))."
  (labels ((recur (count itreap)
             (declare ((integer 0 #.most-positive-fixnum) count))
             (cond ((null itreap) nil)
                   ((funcall order value (%itreap-value itreap))
                    (let ((left-count (- count (itreap-count (%itreap-right itreap)) 1)))
                      (or (recur left-count (%itreap-left itreap))
                          left-count)))
                   (t
                    (recur count (%itreap-right itreap))))))
    (or (recur (itreap-count itreap) itreap)
        (itreap-count itreap))))

(declaim (inline itreap-insort))
(defun itreap-insort (itreap obj order)
  "Does insertion to the sorted treap with keeping the order. You cannot rely on
the side effect. Use the returned value."
  (let ((pos (itreap-bisect-left itreap obj order)))
    (itreap-insert itreap pos obj)))

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/implicit-treap :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

(defun main ()
  (let* ((n (read))
         (m (read))
         (events (make-array n :element-type 'list :initial-element nil))
         (itreap (make-itreap n)))
    (dotimes (i m)
      (let ((l (- (read-fixnum) 1))
            (r (read-fixnum))
            (c (read-fixnum)))
        (push (cons r c) (aref events l))))
    (setf (itreap-ref itreap 0) 0)
    (dotimes (l n)
      #>itreap
      (let ((dist (itreap-ref itreap l)))
        (unless (= dist most-positive-fixnum)
          (loop for (r . c) in (aref events l)
                do (dbg l r c) (itreap-update itreap (+ dist c) l r)))))
    (let ((res (itreap-ref itreap (- n 1))))
      (println (if (= res most-positive-fixnum)
                   -1
                   res)))))

#-swank (main)

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

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    #+os-windows (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)
    #+os-unix (run-program "xsel" '("-b" "-o") :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* (or out (make-string-output-stream)))
         (res (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))))))
    (if out res (get-output-stream-string *standard-output*))))

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

#-swank
(eval-when (:compile-toplevel)
  (when (and (boundp 'sb-c::*compiler-warning-count*)
             (> sb-c::*compiler-warning-count* 0))
    (sb-ext:quit :unix-status 1)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (5am:is
   (equal "5
"
          (run "4 3
1 3 2
2 4 3
1 4 6
" nil)))
  (5am:is
   (equal "-1
"
          (run "4 2
1 2 1
3 4 2
" nil)))
  (5am:is
   (equal "28
"
          (run "10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3
" nil))))

Score : 600 points

Problem Statement

We have N points numbered 1 to N arranged in a line in this order.

Takahashi decides to make an undirected graph, using these points as the vertices.
In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph.
The i-th operation is as follows:

The operation uses integers L_i and R_i between 1 and N (inclusive), and a positive integer C_i. For every pair of integers (s, t) such that L_i \leq s < t \leq R_i, add an edge of length C_i between Vertex s and Vertex t.

The integers L_1, ..., L_M, R_1, ..., R_M, C_1, ..., C_M are all given as input.

Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex 1 to Vertex N in the final graph.

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i < R_i \leq N

1 \leq C_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 C_1
:
L_M R_M C_M

Output

Print the length of the shortest path from Vertex 1 to Vertex N in the final graph.
If there is no shortest path, print -1 instead.

Sample Input 1

4 3
1 3 2
2 4 3
1 4 6

Sample Output 1

5

We have an edge of length 2 between Vertex 1 and Vertex 2, and an edge of length 3 between Vertex 2 and Vertex 4, so there is a path of length 5 between Vertex 1 and Vertex 4.

Sample Input 2

4 2
1 2 1
3 4 2

Sample Output 2

-1

Sample Input 3

10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3

Sample Output 3

28


(in-package :cl-user)
(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 (set-dispatch-macro-character #\# #\> #'cl-debug-print:debug-print-reader)

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

(defconstant +mod+ 1000000007)

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

;; BEGIN_INSERTED_CONTENTS
(defpackage :cp/treap
  (:use :cl)
  (:export #:treap #:treap-count #:treap-find #:treap-bisect-left #:treap-bisect-right-1
           #:treap-split #:treap-insert #:treap-push #:treap-pop #:treap-delete #:treap-merge
           #:treap-map #:invalid-treap-index-error #:treap-first #:treap-last))
(in-package :cp/treap)

;; Not included in test script. Better to use ref-able-treap instead.

(defstruct (treap (:constructor %make-treap (key priority &optional left right))
                  (:copier nil)
                  (:predicate nil)
                  (:conc-name %treap-))
  key
  (priority 0 :type (integer 0 #.most-positive-fixnum))
  (left nil :type (or null treap))
  (right nil :type (or null treap)))

(declaim (inline treap-key))
(defun treap-key (treap)
  (and treap (%treap-key treap)))

(declaim (inline treap-find))
(defun treap-find (key treap &key (order #'<))
  "Searches the sub-treap of TREAP whose key satisfies (and (not (funcall order
key (%treap-key sub-treap))) (not (funcall order (%treap-key sub-treap) key))) and
returns KEY. Returns NIL if KEY is not contained."
  (declare (function order)
           ((or null treap) treap))
  (labels ((recur (treap)
             (cond ((null treap) nil)
                   ((funcall order key (%treap-key treap))
                    (recur (%treap-left treap)))
                   ((funcall order (%treap-key treap) key)
                    (recur (%treap-right treap)))
                   (t key))))
    (recur treap)))

(declaim (inline treap-split))
(defun treap-split (key treap &key (order #'<))
  "Destructively splits the TREAP with reference to KEY and returns two treaps,
the smaller sub-treap (< KEY) and the larger one (>= KEY)."
  (declare (function order)
           ((or null treap) treap))
  (labels ((recur (treap)
             (cond ((null treap)
                    (values nil nil))
                   ((funcall order (%treap-key treap) key)
                    (multiple-value-bind (left right)
                        (recur (%treap-right treap))
                      (setf (%treap-right treap) left)
                      (values treap right)))
                   (t
                    (multiple-value-bind (left right)
                        (recur (%treap-left treap))
                      (setf (%treap-left treap) right)
                      (values left treap))))))
    (recur treap)))

(declaim (inline treap-insert))
(defun treap-insert (key treap &key (order #'<))
  "Destructively inserts KEY into TREAP and returns the resultant treap. You
cannot rely on the side effect. Use the returned value.

The behavior is undefined when duplicate keys are inserted."
  (declare ((or null treap) treap)
           (function order))
  (labels ((recur (new-node treap)
             (declare (treap new-node))
             (cond ((null treap) new-node)
                   ((> (%treap-priority new-node) (%treap-priority treap))
                    (setf (values (%treap-left new-node) (%treap-right new-node))
                          (treap-split (%treap-key new-node) treap :order order))
                    new-node)
                   (t
                    (if (funcall order (%treap-key new-node) (%treap-key treap))
                        (setf (%treap-left treap)
                              (recur new-node (%treap-left treap)))
                        (setf (%treap-right treap)
                              (recur new-node (%treap-right treap))))
                    treap))))
    (recur (%make-treap key (random most-positive-fixnum)) treap)))

(defun treap-map (function treap)
  "Successively applies FUNCTION to each key of TREAP in the given
order. FUNCTION must take one argument."
  (declare (function function))
  (when treap
    (treap-map function (%treap-left treap))
    (funcall function (%treap-key treap))
    (treap-map function (%treap-right treap))))

(defmethod print-object ((object treap) stream)
  (print-unreadable-object (object stream :type t)
    (let ((init t))
      (treap-map (lambda (key)
                   (if init
                       (setf init nil)
                       (write-char #\  stream))
                   (write key :stream stream))
                 object))))

(declaim (ftype (function * (values (or null treap) &optional)) treap-merge))
(defun treap-merge (left right)
  "Destructively concatenates two treaps. Assumes that all keys of LEFT are
smaller (or larger, depending on the order) than those of RIGHT."
  (declare (optimize (speed 3))
           ((or null treap) left right))
  (cond ((null left) right)
        ((null right) left)
        ((> (%treap-priority left) (%treap-priority right))
         (setf (%treap-right left)
               (treap-merge (%treap-right left) right))
         left)
        (t
         (setf (%treap-left right)
               (treap-merge left (%treap-left right)))
         right)))

(declaim (inline treap-delete))
(defun treap-delete (key treap &key (order #'<))
  "Destructively deletes the KEY in TREAP and returns the resultant treap. You
cannot rely on the side effect. Use the returned value."
  (declare ((or null treap) treap)
           (function order))
  (labels ((recur (treap)
             (cond ((null treap) nil)
                   ((funcall order key (%treap-key treap))
                    (setf (%treap-left treap) (recur (%treap-left treap)))
                    treap)
                   ((funcall order (%treap-key treap) key)
                    (setf (%treap-right treap) (recur (%treap-right treap)))
                    treap)
                   (t
                    (treap-merge (%treap-left treap) (%treap-right treap))))))
    (recur treap)))

(defmacro treap-push (key treap order)
  "Pushes KEY to TREAP."
  `(setf ,treap (treap-insert ,key ,treap :order ,order)))

(defmacro treap-pop (key treap order)
  "Deletes KEY from TREAP."
  `(setf ,treap (treap-delete ,key ,treap :order ,order)))

(defun treap-first (treap)
  (declare (optimize (speed 3))
           (treap treap))
  (if (%treap-left treap)
      (treap-first (%treap-left treap))
      (%treap-key treap)))

(defun treap-last (treap)
  (declare (optimize (speed 3))
           (treap treap))
  (if (%treap-right treap)
      (treap-last (%treap-right treap))
      (%treap-key treap)))

(declaim (ftype (function * (values (integer 0 #.most-positive-fixnum) &optional)) treap-count))
(defun treap-count (treap)
  "Counts the number of elements in TREAP in O(n) time."
  (declare (optimize (speed 3))
           ((or null treap) treap))
  (labels ((recur (treap)
             (declare (optimize (safety 0)))
             (if (null treap)
                 0
                 (+ 1
                    (treap-count (%treap-left treap))
                    (treap-count (%treap-right treap))))))
    (recur treap)))

(declaim (inline treap-bisect-left))
(defun treap-bisect-left (treap key &key (order #'<))
  "Returns the smallest key equal to or larger than KEY. Returns NIL if KEY is
larger than any keys in TREAP."
  (declare ((or null treap) treap)
           (function order))
  (labels ((recur (treap)
             (unless treap (return-from recur nil))
             (if (funcall order (%treap-key treap) key)
                 (recur (%treap-right treap))
                 (or (recur (%treap-left treap))
                     treap))))
    (treap-key (recur treap))))

(declaim (inline treap-bisect-right-1))
(defun treap-bisect-right-1 (treap key &key (order #'<))
  "Returns the largest key equal to or smaller than KEY. Returns NIL if KEY is
smaller than any keys in TREAP."
  (declare ((or null treap) treap)
           (function order))
  (labels ((recur (treap)
             (cond ((null treap) nil)
                   ((funcall order key (%treap-key treap))
                    (recur (%treap-left treap)))
                   (t (or (recur (%treap-right treap))
                          treap)))))
    (treap-key (recur treap))))

;; (defun copy-treap (treap)
;;   "For development. Recursively copies the whole TREAP."
;;   (declare ((or null treap) treap))
;;   (if (null treap)
;;       nil
;;       (%make-treap (%treap-key treap)
;;                   (%treap-priority treap)
;;                   (copy-treap (%treap-left treap))
;;                   (copy-treap (%treap-right treap)))))

;; Test
;; (let ((treap1 (%make-treap 50 15))
;;       (treap2 (%make-treap 100 11)))
;;   (setf (%treap-left treap1) (%make-treap 30 5))
;;   (setf (%treap-left (%treap-left treap1)) (%make-treap 20 2))
;;   (setf (%treap-right (%treap-left treap1)) (%make-treap 40 4))
;;   (setf (%treap-right treap1) (%make-treap 70 10))
;;   (setf (%treap-right treap2) (%make-treap 200 3))
;;   (setf (%treap-left treap2) (%make-treap 99 5))
;;   ;; copy-treap
;;   (assert (equalp treap1 (copy-treap treap1)))
;;   (assert (not (eql treap1 (copy-treap treap1))))
;;   ;; split and merge
;;   (let ((treap (treap-merge (copy-treap treap1) (copy-treap treap2))))
;;     (multiple-value-bind (left right) (treap-split 80 (copy-treap treap))
;;       (assert (equalp treap (treap-merge left right)))))
;;   ;; find
;;   (assert (= 40 (treap-find 40 treap1)))
;;   (assert (null (treap-find 41 treap1)))
;;   ;; insert and delete
;;   (let ((inserted-treap1 (treap-insert 41 (copy-treap treap1))))
;;     (assert (= 41 (treap-find 41 inserted-treap1)))
;;     (let ((deleted-treap1 (treap-delete 41 inserted-treap1)))
;;       (assert (null (treap-find 41 deleted-treap1)))
;;       (assert (equalp treap1 deleted-treap1))
;;       (assert (equalp treap1 (treap-delete 41 deleted-treap1))))))

;; (multiple-value-bind (left right) (treap-split 5 (treap-insert 0 (treap-insert 10 (treap-insert 5 nil))))
;;   (assert (= 0 (%treap-key left)))
;;   (assert (null (%treap-left left)))
;;   (assert (null (%treap-right left)))
;;   (assert (or (typep (%treap-left right) 'treap)
;;               (typep (%treap-right right) 'treap))))

;; BEGIN_USE_PACKAGE
(eval-when (:compile-toplevel :load-toplevel :execute)
  (use-package :cp/treap :cl-user))
(in-package :cl-user)

;;;
;;; Body
;;;

;; cには後半1/3をあてるべき
(defun calc (x)
  (ash (* x (+ x 1)) -1))
(defun main ()
  (let* ((n (read))
         (k (read))
         (ab-sum (- (calc (+ k (* 2 n) -1))
                    (calc (+ k -1))))
         (c-sum (- (calc (+ k (* 3 n) -1))
                   (calc (+ k (* 2 n) -1))))
         (out (make-string-output-stream :element-type 'base-char)))
    (dbg ab-sum c-sum)
    (labels ((no () (println -1) (return-from main)))
      (when (> ab-sum c-sum) (no))
      (if (oddp k)
          (let* ((cstart (+ k (* 2 n)))
                 (astart (floor cstart 2))
                 (bstart (+ 1 (floor cstart 2)))
                 rems)
            (dbg astart bstart cstart)
            (loop for a downfrom astart
                  for b from bstart by 2
                  for c from cstart
                  while (and (>= a k) (< b cstart) (< cstart (+ k (* 3 n))))
                  do (unless (= (+ a b) c)
                       (loop))
                     (format out "~D ~D ~D~%" a b c)
                     (dbg a b c)
                  finally (loop for rem-a from a downto k
                                do (push rem-a rems))
                          (loop for rem-b from (+ bstart 1) below cstart by 2
                                do (push rem-b rems))
                          (let (treap)
                            (dolist (rem rems)
                              (treap-push rem treap #'<))
                            (dbg a b c)
                            (loop for rem-c from c below (+ k (* 3 n))
                                  for a = (treap-first treap)
                                  for max-b = (- rem-c a)
                                  for b = (treap-bisect-right-1 treap max-b)
                                  do (dbg rem-c a max-b b)
                                  when (null b)
                                  do (no)
                                  do (format out "~D ~D ~D~%" a b rem-c)
                                     (treap-pop a treap #'<)
                                     (treap-pop b treap #'<))))
            (write-string (get-output-stream-string out)))
          (error "Huh?")))))

#-swank (main)

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

#+swank
(defun get-clipbrd ()
  (with-output-to-string (out)
    #+os-windows (run-program "powershell.exe" '("-Command" "Get-Clipboard") :output out :search t)
    #+os-unix (run-program "xsel" '("-b" "-o") :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* (or out (make-string-output-stream)))
         (res (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))))))
    (if out res (get-output-stream-string *standard-output*))))

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

#-swank
(eval-when (:compile-toplevel)
  (when (and (boundp 'sb-c::*compiler-warning-count*)
             (> sb-c::*compiler-warning-count* 0))
    (sb-ext:quit :unix-status 1)))

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (5am:is
   (equal "1 2 3
"
          (run "1 1
" nil)))
  (5am:is
   (equal "-1
"
          (run "3 3
" nil))))

Score : 700 points

Problem Statement

Given are positive integers N and K.

Determine if the 3N integers K, K+1, ..., K+3N-1 can be partitioned into N triples (a_1,b_1,c_1), ..., (a_N,b_N,c_N) so that the condition below is satisfied. Any of the integers K, K+1, ..., K+3N-1 must appear in exactly one of those triples.

For every integer i from 1 to N, a_i + b_i \leq c_i holds.

If the answer is yes, construct one such partition.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq 10^9

Input

Input is given from Standard Input in the following format:

N K

Output

If it is impossible to partition the integers satisfying the condition, print -1. If it is possible, print N triples in the following format:

a_1 b_1 c_1
:
a_N b_N c_N

Sample Input 1

1 1

Sample Output 1

1 2 3

Sample Input 2

3 3

Sample Output 2

-1


(let* ((s (read-line))
       (x (make-array (list (length s)) :adjustable t :fill-pointer 0))
       (ans 0))
  (loop :with c := #\=
        :with p := -1
        :for y :across s
        :if (char/= c y)
        :do (progn
              (vector-push-extend 0 x)
              (incf p)
              (setf c y))
        :do (if (char= y #\<)
                (incf (aref x p))
                (decf (aref x p))))
  (loop :for v :across x
        :for w := (abs v)
        :for i :from 0
        :do (incf ans (/ (* w (- w 1)) 2))
        :if (> v 0)
        :do (incf ans (if (= (1+ i) (length x)) w (max w (abs (aref x (1+ i)))))))
  (when (< (aref x 0) 0)
    (incf ans (aref x 0)))
  (format t "~A~%" ans))

Score : 300 points

Problem Statement

Given is a string S of length N-1.
Each character in S is < or >.

A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1):

If S_i= <: a_i<a_{i+1}

If S_i= >: a_i>a_{i+1}

Find the minimum possible sum of the elements of a good sequence of N non-negative integers.

Constraints

2 \leq N \leq 5 \times 10^5

S is a string of length N-1 consisting of < and >.

Input

Input is given from Standard Input in the following format:

S

Output

Find the minimum possible sum of the elements of a good sequence of N non-negative integers.

Sample Input 1

<>>

Sample Output 1

3

a=(0,2,1,0) is a good sequence whose sum is 3.
There is no good sequence whose sum is less than 3.

Sample Input 2

<>>><<><<<<<>>><

Sample Output 2

28


(defun f(s)
  (labels ((rec(i lastc n acc)
             (format t "~A ~A ~A ~A~%" i lastc n acc)
             (if (= i (length s))
               (+ (/ (* n (1+ n)) 2) acc)
               (if (char= (char s i) lastc)
                 (rec (1+ i) lastc (1+ n) acc)
                 (if (= n 1)
                   (if (char= (char s i) #\>)
                     (rec (1+ i) (char s i) 1 acc)
                     (rec (1+ i) (char s i) 1 (1+ acc)))
                   (if (char= (char s i) #\<)
                     (rec (1+ i) (char s i) 1 (+ acc (/ (* n (1+ n)) 2)))
                     (rec (1+ i) (char s i) 0 (+ acc (/ (* n (1+ n)) 2)))
                     ))))))
    (rec 1 (char s 0) 1 0)))
(let ((line (read-line nil nil)))
  (format t "~A~%" (f line)))