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

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

;; BEGIN_INSERTED_CONTENTS
;;;
;;; Persistent segment tree
;;;

;; TODO:
;; - abstraction
;; - test
;; - linear-time initialization
;; - avoid sb-int:power-of-two-ceiling
;; - out-of-bound error

(defparameter *store* (make-array 200000000 :element-type 'uint31))
(declaim ((simple-array uint31 (*)) *store*)
         (always-bound *store*))
(defparameter *end* 0)
(declaim ((mod #.array-total-size-limit) *end*)
         (always-bound *end*))

(declaim (inline node-value))
(defun node-value (node)
  (the uint31 (aref *store* node)))
(declaim (inline (setf node-value)))
(defun (setf node-value) (new-value node)
  (declare (uint31 new-value))
  (setf (aref *store* node) new-value))
(declaim (inline node-left))
(defun node-left (node)
  (declare ((mod #.array-total-size-limit) node))
  (aref *store* (+ node 1)))
(declaim (inline (setf node-left)))
(defun (setf node-left) (new-value node)
  (setf (aref *store* (+ node 1)) new-value))
(declaim (inline node-right))
(defun node-right (node)
  (declare ((mod #.array-total-size-limit) node))
  (aref *store* (+ node 2)))
(declaim (inline (setf node-right)))
(defun (setf node-right) (new-value node)
  (setf (aref *store* (+ node 2)) new-value))

(declaim (inline make-node))
(defun make-node (&optional (value 0))
  (let ((end *end*))
    (when (= end (length *store*))
      (setq *store* (adjust-array *store* (* 2 end))))
    (setf (aref *store* end) value)
    (incf *end* 3)
    end))

(declaim (inline copy-node))
(defun copy-node (node)
  (let ((end *end*))
    (when (= end (length *store*))
      (setq *store* (adjust-array *store* (* 2 end))))
    (setf (aref *store* end) (aref *store* node)
          (aref *store* (+ end 1)) (aref *store* (+ node 1))
          (aref *store* (+ end 2)) (aref *store* (+ node 2)))
    (incf *end* 3)
    end))

(defstruct (psegtree (:constructor %make-psegtree)
                     (:conc-name %psegtree-))
  (length 0 :type (mod #.array-total-size-limit))
  (root 0 :type (mod #.array-total-size-limit)))

(defun make-psegtree (length)
  "Note that the actual length becomes a power of two."
  (declare ((integer 0 #.most-positive-fixnum) length))
  (let ((n (ash 1 (integer-length (- length 1))))) ; power of two ceiling
    (labels ((recur (i)
               (declare (uint31 i))
               (if (<= i n)
                   (let ((node (make-node)))
                     (setf (node-left node) (recur (ash i 1))
                           (node-right node) (recur (ash i 1)))
                     node)
                   0)))
      (%make-psegtree :length length :root (recur 1)))))

(defun psegtree-query (psegtree left right)
  "Queries the sum of the interval [LEFT, RIGHT)."
  (declare #.opt
           (uint31 left right))
  (labels ((recur (root l r)
             (declare (uint31 l r)
                      (values uint31 &optional))
             (cond ((or (<= right l) (<= r left))
                    0)
                   ((and (<= left l) (<= r right))
                    (node-value root))
                   (t
                    (+ (recur (node-left root) l (ash (+ l r) -1))
                       (recur (node-right root) (ash (+ l r) -1) r))))))
    (recur (%psegtree-root psegtree)
           0
           (sb-int:power-of-two-ceiling (%psegtree-length psegtree)))))

(defun psegtree-inc (psegtree index delta)
  "Returns a new psegtree updated by PSEGTREE[INDEX] += DELTA. This function is
non-destructive."
  (declare #.opt
           (uint31 index)
           (int32 delta))
  (labels ((recur (root l r)
             (declare (int32 l r))
             (cond ((or (<= (+ index 1) l) (<= r index)))
                   ((and (<= index l) (<= r (+ index 1)))
                    (incf (node-value root) delta))
                   (t
                    (let ((new-lnode (copy-node (node-left root)))
                          (new-rnode (copy-node (node-right root))))
                      (setf (node-left root) new-lnode
                            (node-right root) new-rnode)
                      (recur new-lnode l (ash (+ l r) -1))
                      (recur new-rnode (ash (+ l r) -1) r)
                      (setf (node-value root)
                            (+ (node-value (node-left root))
                               (node-value (node-right root)))))))))
    (let ((new-psegtree (copy-psegtree psegtree))
          (new-root (copy-node (%psegtree-root psegtree))))
      (recur new-root 0 (sb-int:power-of-two-ceiling (%psegtree-length psegtree)))
      (setf (%psegtree-root new-psegtree) new-root)
      new-psegtree)))

(defmethod print-object ((object psegtree) stream)
  (print-unreadable-object (object stream :type t)
    (let ((init t)
          (length (%psegtree-length object)))
      (labels ((recur (node index)
                 (if (node-left node)
                     (progn
                       (recur (node-left node) (ash index 1))
                       (recur (node-right node) (+ (ash index 1) 1)))
                     (when (< index length)
                       (if init
                           (setq init nil)
                           (write-char #\  stream))
                       (write (node-value node) :stream stream)))))
        (recur (%psegtree-root object) 0)))))

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

(in-package :cl-user)

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

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

(defun main ()
  (declare #.opt)
  (let* ((n (read))
         (q (read))
         (cs (make-array n :element-type 'uint31 :initial-element 0))
         (ls (make-array q :element-type 'uint31 :initial-element 0))
         (rs (make-array q :element-type 'uint31 :initial-element 0))
         (appeared (make-array (+ n 1) :element-type 'uint31 :initial-element +nan+))
         (psegtrees (make-array (+ n 1) :element-type t)))
    (dotimes (i n)
      (setf (aref cs i) (read-fixnum)))
    (dotimes (i q)
      (setf (aref ls i) (- (read-fixnum) 1)
            (aref rs i) (read-fixnum)))
    (setf (aref psegtrees 0) (make-psegtree n))
    (dotimes (i n)
      (let ((c (aref cs i)))
        (setf (aref psegtrees (+ i 1))
              (psegtree-inc (aref psegtrees i) i 1))
        (unless (= +nan+ (aref appeared c))
          (setf (aref psegtrees (+ i 1))
                (psegtree-inc (aref psegtrees (+ i 1)) (aref appeared c) -1)))
        (setf (aref appeared c) i)))
    (write-string
     (with-output-to-string (*standard-output* nil :element-type 'base-char)
       (loop for l across ls
             for r across rs
             for psegtree = (aref psegtrees r)
             do (println (psegtree-query psegtree l r)))))))


;; #+linux
;; (eval-when (:compile-toplevel :load-toplevel :execute)
;;   (require :sb-sprof))
;; #+linux
;; (sb-sprof:start-profiling)

#-swank (main)

;; #+linux
;; (progn
;;   (sb-sprof:stop-profiling)
;;   (sb-sprof:report))

#-swank (main)

#+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)
    #+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* 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)
    (let ((n 500000)
          (q 500000))
      (format out "~D ~D~%" n q)
      (dotimes (_ n)
        (println (+ 1 (random 500000)) out))
      (dotimes (_ q)
        (let ((l (+ 1 (random 500000)))
              (r (+ 1 (random 500000))))
          (when (> l r)
            (rotatef l r))
          (format out "~D ~D~%" l r))))))

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

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


Measured memory_bytes: 543200