Problem:
Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the response to the i-th query.

Sample Input 1

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

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

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

Sample Output 2

1
2
2
1
2
2
6
3
3
3

Solution in Common Lisp (SBCL 2.0.3) (judge verdict: Accepted)

(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
;;;
;;; Quicksort (deterministic median-of-three partitioning)
;;;

;; NOTE: This quicksort is NOT randomized. You should shuffle an input when you
;; need to avoid getting hacked.

;; Reference:
;; Hannu Erkio, The worst case permutation for median-of-three quicksort

(declaim (inline %median3))
(defun %median3 (x y z order)
  (if (funcall order x y)
      (if (funcall order y z)
          y
          (if (funcall order z x)
              x
              z))
      (if (funcall order z y)
          y
          (if (funcall order x z)
              x
              z))))

(declaim (inline quicksort!))
(defun quicksort! (vector order)
  "Destructively sorts VECTOR w.r.t. ORDER."
  (declare (vector vector))
  (labels
      ((recur (left right)
         (when (< left right)
           (let* ((l left)
                  (r right)
                  (pivot (%median3 (aref vector l)
                                   (aref vector (ash (+ l r) -1))
                                   (aref vector r)
                                   order)))
             (declare ((integer 0 #.most-positive-fixnum) l r))
             (loop (loop while (funcall order (aref vector l) pivot)
                         do (incf l))
                   (loop while (funcall order pivot (aref vector r))
                         do (decf r))
                   (when (>= l r)
                     (return))
                   (rotatef (aref vector l) (aref vector r))
                   (incf l 1)
                   (decf r 1))
             (recur left (- l 1))
             (recur (+ r 1) right)))))
    (recur 0 (- (length vector) 1))
    vector))

;;;
;;; Mo's algorithm
;;;

(deftype mo-integer () 'uint31)

(defstruct (mo (:constructor %make-mo
                   (lefts rights order))
               (:conc-name %mo-)
               (:copier nil)
               (:predicate nil))
  (lefts nil :type (simple-array mo-integer (*)))
  (rights nil :type (simple-array mo-integer (*)))
  (order nil :type (simple-array mo-integer (*)))
  (index 0 :type (integer 0 #.most-positive-fixnum)))

(defun make-mo (bucket-width lefts rights)
  "LEFTS := vector of indices of left-end of queries (inclusive)
RIGHTS := vector of indices of right-end of queries (exclusive)

BUCKET-WIDTH would be better set to N/sqrt(Q) where N is the width of the
universe and Q is the number of queries."
  (declare #.opt
           ((simple-array mo-integer (*)) lefts rights)
           ((integer 0 #.most-positive-fixnum) bucket-width)
           (inline sort))
  (let* ((q (length lefts))
         (order (make-array q :element-type 'mo-integer)))
    (assert (= q (length rights)))
    (dotimes (i q) (setf (aref order i) i))
    (quicksort! order
                (lambda (x y)
                  (if (= (floor (aref lefts x) bucket-width)
                         (floor (aref lefts y) bucket-width))
                      ;; Even-number [Odd-number] block is in ascending
                      ;; [descending] order w.r.t. the right end.
                      (if (evenp (floor (aref lefts x) bucket-width))
                          (< (aref rights x) (aref rights y))
                          (> (aref rights x) (aref rights y)))
                      (< (aref lefts x) (aref lefts y)))))
    (%make-mo lefts rights order)))

(declaim (inline mo-get-current))
(defun mo-get-current (mo)
  "Returns the original index of the current (not yet proessed) query."
  (aref (%mo-order mo) (%mo-index mo)))

(declaim (ftype (function * (values uint31 &optional)) read-fixnum+))
(defun read-fixnum+ (&optional (in *standard-input*))
  "NOTE: cannot read -2^62"
  (declare #.opt
           (sb-kernel:ansi-stream in))
  (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* ((result (loop (let ((byte (%read-byte)))
                           (when (<= 48 byte)
                             (return (- byte 48)))))))
      (declare (uint31 result))
      (loop
        (let* ((byte (%read-byte)))
          (if (<= 48 byte)
              (setq result (+ (- byte 48)
                              (* 10 (the uint31 result))))
              (return 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
;;;

(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)))
    (dotimes (i n)
      (setf (aref cs i) (read-fixnum+)))
    (dotimes (i q)
      (setf (aref ls i) (- (read-fixnum+) 1)
            (aref rs i) (read-fixnum+)))
    (let ((mo (make-mo 740 ls rs))
          (dp (make-array (+ n 1) :element-type 'uint31))
          (res (make-array q :element-type 'uint31 :initial-element 0))
          (value 0)
          (posl 0)
          (posr 0))
      (declare (uint31 value))
      (dotimes (_ q)
        (let* ((ord (mo-get-current mo))
               (left (aref ls ord))
               (right (aref rs ord)))
          (declare ((integer 0 #.most-positive-fixnum) posl posr))
          (loop while (< left posl)
                do (decf posl)
                   (let* ((c (aref cs posl))
                          (num (aref dp c)))
                     (when (zerop num)
                       (incf value))
                     (setf (aref dp c) (+ num 1))))
          (loop while (< posr right)
                do (let* ((c (aref cs posr))
                          (num (aref dp c)))
                     (when (zerop num)
                       (incf value))
                     (setf (aref dp c) (+ num 1)))
                   (incf posr))
          (loop while (< posl left)
                do (let* ((c (aref cs posl))
                          (num (aref dp c)))
                     (when (= 1 num)
                       (decf value))
                     (setf (aref dp c) (- num 1)))
                   (incf posl))
          (loop while (< right posr)
                do (decf posr)
                   (let* ((c (aref cs posr))
                          (num (aref dp c)))
                     (when (= 1 num)
                       (decf value))
                     (setf (aref dp c) (- num 1))))
          (incf (%mo-index mo))
          (setf (aref res ord) value)))
      (write-string
       (with-output-to-string (*standard-output* nil :element-type 'base-char)
         (loop for x across res
               do (println x)))))))

#-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)
    #+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)
    (format out "")))

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

;; To run: (5am:run! :sample)
#+swank
(it.bese.fiveam:test :sample
  (it.bese.fiveam:is
   (common-lisp-user::io-equal "4 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
")))