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 C++ (GCC 9.2.1) (judge verdict: Accepted)

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll n,q,v[500001],aib[500001],sol[500001];
vector<int> pos[500001];
struct date
{
    ll l,r,poz;
};
date qry[500001];
ll lsb(ll x)
{
    return x&(-x);
}
void update(ll poz, ll val)
{
    for(int i=poz;i<=n;i+=lsb(i))
        aib[i]+=val;
}
ll query(ll poz)
{
    ll rez=0;
    for(int i=poz;i>=1;i-=lsb(i))
        rez+=aib[i];
    return rez;
}
bool comp(date a, date b)
{
    if(a.l!=b.l)
        return a.l<b.l;
    return a.r<b.r;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>q;
    for(int i=1;i<=n;i++)
        cin>>v[i];
    for(int i=1;i<=q;i++)
    {
        cin>>qry[i].l>>qry[i].r;
        qry[i].poz=i;
    }
    sort(qry+1,qry+q+1,comp);
    for(int i=n;i>=1;i--)
        pos[v[i]].push_back(i);
    for(int i=1;i<=n;i++)
        if(!pos[i].empty())
            update(pos[i].back(),1);
    ll st=1;
    for(int i=1;i<=q;i++)
    {
        while(st<qry[i].l)
        {
            update(st,-1);
            pos[v[st]].pop_back();
            if(!pos[v[st]].empty())
                update(pos[v[st]].back(),1);
            st++;
        }
        sol[qry[i].poz]=query(qry[i].r);
    }
    for(int i=1;i<=q;i++)
        cout<<sol[i]<<'\n';
    return 0;
}