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 Rust (1.42.0) (judge verdict: Accepted)

pub trait MoState {
    type Elem;
    type Answer;
    fn new() -> Self;
    fn clear(&mut self);
    fn get_ans(&self) -> Self::Answer;
    fn add_right(&mut self, e: &Self::Elem);
    fn add_left(&mut self, e: &Self::Elem);
    fn delete_right(&mut self, e: &Self::Elem);
    fn delete_left(&mut self, e: &Self::Elem);
}

pub struct Mo<M: MoState> {
    q: usize,
    bsz: usize,
    qsl: usize,
    qs: Vec<Vec<Vec<(usize, usize, usize)>>>, 
    v: Vec<M::Elem>,
}

impl<M: MoState> Mo<M> {
    pub fn new<I>(n: usize, bucket_sz: usize, iter: I) -> Self 
    where
        I: IntoIterator<Item = M::Elem>
    {
        let qsl = (n + bucket_sz - 1) / bucket_sz;
        Self {
            q: 0,
            bsz: bucket_sz,
            qsl,
            qs: vec![vec![Vec::new(); qsl]; qsl],
            v: iter.into_iter().collect(),
        }
    }

    pub fn add_query(&mut self, l: usize, r: usize) -> usize {
        let i = self.q;
        self.qs[l / self.bsz][r / self.bsz].push((r, l, i));
        self.q += 1;
        i
    }

    pub fn build(&mut self) {
        for s in 0..self.qs.len() {
            for t in 0..self.qs[s].len() {
                self.qs[s][t].sort_unstable();
            }
        }
    }

    pub fn run(&self) -> Vec<Option<M::Answer>> {
        let mut ans: Vec<_> = (0..self.q).map(|_| None).collect();
        let mut state = M::new();
        for s in 0..self.qs.len() {
            state.clear();
            let mut l = s * self.bsz;
            let mut r = l;
            for t in 0..self.qs[s].len() {
                for &(qr, ql, qi) in self.qs[s][t].iter() {
                    while r < qr { state.add_right(&self.v[r]); r += 1; }
                    while l > ql { l -= 1; state.add_left(&self.v[l]); }
                    while r > qr { r-= 1; state.delete_right(&self.v[r]); }
                    while l < ql { state.delete_left(&self.v[l]); l += 1; }
                    ans[qi] = Some(state.get_ans());
                }
            }
        }
        ans
    }

}

struct MoKind {
    cnt: Vec<i32>,
    ans: i32,
}

impl MoState for MoKind {
    type Elem = usize;
    type Answer = i32;
    fn new() -> Self {
        Self { cnt: vec![0; 505050], ans: 0 }
    }
    fn clear(&mut self) {
        self.cnt.iter_mut().map(|x| *x = 0).count();
        self.ans = 0;
    }
    fn get_ans(&self) -> Self::Answer {
        self.ans
    }
    fn add_right(&mut self, e: &Self::Elem) {
        if self.cnt[*e] == 0 { self.ans += 1 }
        self.cnt[*e] += 1;
    }
    fn add_left(&mut self, e: &Self::Elem) {
        if self.cnt[*e] == 0 { self.ans += 1 }
        self.cnt[*e] += 1;
    }
    fn delete_right(&mut self, e: &Self::Elem) {
        self.cnt[*e] -= 1;
        if self.cnt[*e] == 0 { self.ans -= 1; }
    }
    fn delete_left(&mut self, e: &Self::Elem) {
        self.cnt[*e] -= 1;
        if self.cnt[*e] == 0 { self.ans -= 1; }
    }
}

fn main() {
    ioset! { inp, buf }
    macro_rules! scan {
        ($($r:tt)*) => {
            input! { inp, $($r)* }
        }
    }
    macro_rules! print {
        ($($t:expr),*) => {
            write!(buf, $($t),*).unwrap();
        } 
    }

    scan! {
        n: usize,
        q: usize,
        c: [usize; n],
        r: [(usize, usize); q],
    }
    let mut mo = Mo::<MoKind>::new(n, 1024, c);
    for (l, r) in r {
        mo.add_query(l - 1, r);
    }
    //mo.build();
    let ans = mo.run();
    for a in ans {
        print!("{}\n", a.unwrap());
    }
}

use std::io::{ stdout, BufWriter, Write };

#[macro_export]
macro_rules! ioset {
    ($inp:ident, $buf:ident) => {
        inset!($inp);
        outset!($buf);
    }
}

#[macro_export]
macro_rules! inset {
    (source = $s:expr, $iter:ident) => {
        let mut $iter = $s.split_whitespace();
    };
    ($iter:ident) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut $iter = s.split_whitespace();
    }
}

#[macro_export]
macro_rules! input {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt, $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input! { $iter, $($r)* }
    };
    ($iter:expr, mut $var:ident : $t:tt, $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input! { $iter, $($r)* }
    };
    ($iter:expr, ($var:expr) : $t:tt, $($r:tt)*) => {
        $var = read_value!($iter, $t);
        input! { $iter, $($r)* }
    };
}

#[macro_export]
macro_rules! read_value {

    // tuple
    ($iter:expr, ( $($t:tt), * )) => {
        ( $(read_value!($iter, $t)), * )
    };
    
    // array
    ($iter:expr, [ $t:tt; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    
    // string
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    
    // any other
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[macro_export]
macro_rules! outset {
    ($buf:ident) => {
        let sout = stdout();
        let mut $buf = BufWriter::new(sout.lock());
    }
}

#[macro_export]
macro_rules! output {
    ($buf:expr, $($t:expr),*) => {
        write!($buf, $($t),*).unwrap();
    }
}

struct Chars<'a>(&'a Vec<char>);

impl<'a> std::fmt::Display for Chars<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(f, "{}", self.0.iter().collect::<String>())
    }
}

use std::cmp::Ordering;

pub trait BinarySearch<T> {
    fn lower_bound(&self, x: &T) -> usize;
    fn upper_bound(&self, x: &T) -> usize;
}

impl<T: Ord> BinarySearch<T> for [T] {
    fn lower_bound(&self, x: &T) -> usize {
        let mut ng = -1i64;
        let mut ok = self.len() as i64;
        while ok - ng > 1 {
            let m = (ok + ng) / 2;
            match self[m as usize].cmp(x) {
                Ordering::Greater | Ordering::Equal => {
                    ok = m;
                }
                _ => {
                    ng = m;
                }
            }
        }
        ok as usize
    }
    fn upper_bound(&self, x: &T) -> usize {
        let mut ng = -1i64;
        let mut ok = self.len() as i64;
        while ok - ng > 1 {
            let m = (ok + ng) / 2;
            match self[m as usize].cmp(x) {
                Ordering::Greater => {
                    ok = m;
                }
                _ => {
                    ng = m;
                }
            }
        }
        ok as usize
    }
}