SPOJ - DQUERY

D-query 

Given a sequence of n numbers a1, a2, ..., an and a number of d-queries. A d-query is a pair (i, j) (1 ≤ i ≤ j ≤ n). For each d-query (i, j), you have to return the number of distinct elements in the subsequence ai, ai+1, ..., aj.

Input

  • Line 1: n (1 ≤ n ≤ 30000).
  • Line 2: n numbers a1, a2, ..., an (1 ≤ ai ≤ 106).
  • Line 3: q (1 ≤ q ≤ 200000), the number of d-queries.
  • In the next q lines, each line contains 2 numbers i, j representing a d-query (1 ≤ i ≤ j ≤ n).

Output

  • For each d-query (i, j), print the number of distinct elements in the subsequence ai, ai+1, ..., aj in a single line.

Example

Input
5
1 1 2 1 3
3
1 5
2 4
3 5

Output
3
2
3 

之前用主席树写过这个题,最近学习了莫队,就用莫队来写了下这个。

莫队算法的精髓就是通过合理地对询问排序,然后以较优的顺序暴力回答每个询问。处理完一个询问后,可以使用它的信息得到下一个询问区间的答案。  考虑这个问题:对于上面这道题,已知区间 [1,5] 的答案,求 [2,6] 的答案,如何暴力求?  当然,可以将区间 [2,6] 从头到尾扫一遍,直接求出答案,也可以在区间 [1,5] 的基础上,去掉位置1(即将左端点右移一位),加上位置6(即将右端点右移一位)

#include<bits/stdc++.h>
using namespace std;
const int maxn = 200000+5;
int unit,ans,cnt[1000005],res[maxn],a[30005];
struct node
{
    int l,r,id;
    bool friend operator < (const node u,const node v)
    {
        if(u.l/unit==v.l/unit)
            return u.r<v.r;
        else return u.l/unit>v.l/unit;
    }
} p[maxn];
void add(int x)
{
    cnt[a[x]]++;
    if(cnt[a[x]]==1)
        ans++;
}
void Remove(int x)
{
    cnt[a[x]]--;
    if(cnt[a[x]]==0)
        ans--;
}
int main()
{
    int n,m;
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
    {
        scanf("%d",&a[i]);
    }
    unit = sqrt(n);
    scanf("%d",&m);
    for(int i=1; i<=m; i++)
    {
        scanf("%d %d",&p[i].l,&p[i].r);
        p[i].id=i;
    }
    sort(p+1,p+1+m);
    int L=1,R=0;
    ans=0;
    for(int i=1; i<=m; i++)
    {
        while(L<=p[i].l) Remove(L++);
        while(L>p[i].l) add(--L);
        while(R<=p[i].r) add(++R);
        while(R>p[i].r) Remove(R--);

        res[p[i].id]=ans;
    }
    for(int i=1; i<=m; i++)
        printf("%d\n",res[i]);
}

 PS:摸鱼怪的博客分享,欢迎感谢各路大牛的指点~

猜你喜欢

转载自www.cnblogs.com/MengX/p/9345850.html