Fast Queries

Given an array of N integers indexed from 1 to N, and q queries, each in the form i j, you have to find the number of distinct integers from index i to j (inclusive).

Input

Input starts with an integer T (≤ 5), denoting the number of test cases.

The first line of a case is a blank line. The next line contains two integers N (1 ≤ N ≤ 105)q (1 ≤ q ≤ 50000). The next line contains N space separated integers forming the array. There integers range in [0, 105].

Each of the next q lines will contain a query which is in the form i j (1 ≤ i ≤ j ≤ N).

Output

For each test case, print the case number in a single line. Then for each query you have to print a line containing number of distinct integers from index i to j.

Sample Input

1

 

8 5

1 1 1 2 3 5 1 2

1 8

2 3

3 6

4 5

4 8

Sample Output

Case 1:

4

1

4

2

4

Note

Dataset is huge. Use faster I/O methods.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define maxn 200005
#define ll long long
using namespace std;
struct mo
{
    ll l,r,id;
    ll a;
}p[maxn];
 ll ans=0;
 ll mark[maxn];
 ll pos[maxn];
 ll a[maxn];
int t;
ll n,m;
 void add(ll i)
 {if(mark[a[i]]==0)
     ans++;
     mark[a[i]]++;
 }
 void del(ll i)
 {
     mark[a[i]]--;
     if(mark[a[i]]==0)
     ans--;
 }

 bool cmp1(mo a,mo b)
 {
     return pos[a.l]==pos[b.l]?a.r<b.r:a.l<b.l;
 }
 bool cmp2(mo a,mo b)
 {
     return a.id<b.id;
 }
 int main()
{scanf("%d",&t);
int w=0;
    while(t--)
    {w++;
    printf("Case %d:\n",w);
        scanf("%lld%lld",&n,&m);
        memset(mark,0,sizeof(mark));
    memset(pos,0,sizeof(pos));
    ans=0;
    ll b=sqrt(1.0*n);
        for(ll i=1;i<=n;i++)
        {scanf("%d",&a[i]);
        pos[i]=i/b;
    }
    for(ll i=1;i<=m;i++)
{
    scanf("%lld%lld",&p[i].l,&p[i].r);
    p[i].id=i;
}
sort(p+1,p+m+1,cmp1);
ll l=1,r=0;
for(ll i=1;i<=m;i++)
{
    while(l<p[i].l)
    {
        del(l++);
    }
    while(l>p[i].l)
    {
        add(--l);
    }
    while(r>p[i].r)
    {
        del(r--);
    }
    while(r<p[i].r)
    {
        add(++r);
    }
    p[i].a=ans;


}
sort(p+1,p+m+1,cmp2);
for(ll i=1;i<=m;i++)
    printf("%lld\n",p[i].a);
    }
return 0;

}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/88358350