SPOJ DQUERY D-query(主席树)

题目

Source

http://www.spoj.com/problems/DQUERY/en/

Description

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.

Sample Input

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

Sample Output

3
2
3

 

分析

题目说给一个序列,多次询问一个区间内不同数的个数。

 

离线做法很经典吧,HDU3333
主席树做法。。其实很容易往建权值线段树那边想,不过好像行不通。。

 

其实做法也和离线是一样的,线段树维护的是各个位置是否要存在数,记录各个数出现最右边的位置,删除之前的位置、更新当前位置,相当于把各个数字一直往右靠。

于是这样就从左往右保存了多个版本的线段树信息,查询时就拿出右端点对应版本的线段树进行区间查询。

 

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define MAXN 33333

int x,y,root[MAXN],tree[MAXN*20],lch[MAXN*20],rch[MAXN*20],N;

void update(int i,int j,int a,int &b){
    b=++N;
    if(i==j){
        tree[b]=tree[a]+y;
        return;
    }
    int mid=i+j>>1;
    lch[b]=lch[a]; rch[b]=rch[a];
    if(x<=mid) update(i,mid,lch[a],lch[b]);
    else update(mid+1,j,rch[a],rch[b]);
    tree[b]=tree[lch[b]]+tree[rch[b]];
}
int query(int i,int j,int a){
    if(x<=i && j<=y){
        return tree[a];
    }
    int mid=i+j>>1,ret=0;
    if(x<=mid) ret+=query(i,mid,lch[a]);
    if(y>mid) ret+=query(mid+1,j,rch[a]);
    return ret;
}

int a[MAXN],last[1111111];
int main(){
    int n,q;
    scanf("%d",&n);
    for(int i=1; i<=n; ++i){
        scanf("%d",&a[i]);
    }

    for(int i=1; i<=n; ++i){
        if(last[a[i]]){
            int tmp; x=last[a[i]]; y=-1;
            update(1,n,root[i-1],tmp);
            x=i; y=1;
            update(1,n,tmp,root[i]);
        }else{
            x=i; y=1;
            update(1,n,root[i-1],root[i]);
        }
        last[a[i]]=i;
    }

    scanf("%d",&q);
    while(q--){
        scanf("%d%d",&x,&y);
        printf("%d\n",query(1,n,root[y]));
    }
    return 0;
}

 

posted @ 2016-10-07 16:19  WABoss  阅读(376)  评论(0编辑  收藏  举报