SPOJ D-query(主席树应用)

本文介绍了一种解决区间内不同元素计数问题的有效算法。通过使用离散化和树状结构,该方法能够快速响应大量区间查询,适用于编程竞赛及实际应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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 


题意:

给出n,然后是n个数,再给出m,m个询问,对于每个询问l,r,输出区间[l,r]里面不同的值有多少个。


题解:

可以用一个map离散化,倒着对序列进行操作,对于每个i建树时,如果a[i]出现过,则在map[a[i]]处减去1,然后询问时直接对根为root[l]的树进行询问就可以了。


#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define fi first
#define se second
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const int inf=0x3fffffff;
const ll mod=1000000007;
const int maxn=30000+100;
int n,m,cnt,a[maxn],root[maxn];
struct node{int l,r,sum;}T[maxn*40];
map<int,int> mp;
void update(int l,int r,int& x,int y,int pos,int val)
{
    T[++cnt]=T[y],T[cnt].sum+=val;
    x=cnt;
    if(l==r) return;
    int mid=(l+r)/2;
    if(pos<=mid) update(l,mid,T[x].l,T[y].l,pos,val);
    else update(mid+1,r,T[x].r,T[y].r,pos,val);
}
int query(int l,int r,int root,int k)
{
    int ans=0;
    if(l==r) return T[root].sum;
    int mid=(l+r)/2;
    if(mid<k) return T[T[root].l].sum+query(mid+1,r,T[root].r,k);
    else return query(l,mid,T[root].l,k);
}
int main()
{
    scanf("%d",&n);
    rep(i,1,n+1) scanf("%d",&a[i]);
    mp.clear();
    per(i,1,n+1)
    {
        if(mp.find(a[i])==mp.end())
        {
            update(1,n,root[i],root[i+1],i,1);
        }
        else
        {
            update(1,n,root[i],root[i+1],mp[a[i]],-1);
            update(1,n,root[i],root[i],i,1);
        }
        mp[a[i]]=i;
    }
    scanf("%d",&m);
    while(m--)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%d\n",query(1,n,root[x],y));
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值