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)

// after YouTube editorial
// Binary Indexed Tree (Fenwick Tree)
// https://youtu.be/lyHk98daDJo?t=7960
use proconio::{input, fastout};

#[derive(Debug)]
struct BIT {
    n: usize,
    d: Vec<i32>,
}

impl BIT {
    fn new(i: usize) -> BIT {
        BIT {n: i, d: vec![0; i+1]}
    }
    fn add(&mut self, mut i: usize, x :i32) {
        i += 1;
        while i <= self.n {
            self.d[i] += x;
            i += i & (-(i as i64))as usize;
        }
    }
    fn sum(&self, mut i: usize) -> i32 {
        let mut x = 0;
        i += 1;
        while i > 0 {
            x += self.d[i];
            i -= i & (-(i as i64))as usize;
        }
        x 
    }
}

#[fastout]
fn main() {
    input! {
        n: usize, q: usize,
        c: [i32; n],
        lr: [(i32, i32); q],
    }
    let mut pi: Vec<i32> = vec![-1; n+1];
    let mut ps: Vec<Vec<i32>> = vec![vec![]; n];
    for i in 0..n {
        let l = pi[c[i]as usize];
        if l != -1 { ps[l as usize].push(i as i32) };
        pi[c[i]as usize] = i as i32;
    }
    let mut qs: Vec<Vec<(i32,i32)>> = vec![vec![]; n];
    for i in 0..q {
        let (mut l, mut r) = lr[i];
        l -= 1;
        r -= 1;
        qs[l as usize].push( (r,i as i32) );
    }
    let mut ans: Vec<i32> = vec![-1; q];
    let mut d = BIT::new(n);
    for x in (0..n).rev() {
        for y in ps[x].iter() { d.add(*y as usize,1) }
        for qq in qs[x].iter() {
            let r = (&qq).0;
            let i = (&qq).1;
            ans[i as usize] = r - x as i32 + 1 - d.sum(r as usize);
        }
    }
    for a in ans.iter() {
        println!("{}", *a);
    }
}