首页 > 代码库 > SPOJ DQUERY - D-query

SPOJ DQUERY - D-query

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

Input51 1 2 1 331 52 43 5Output323 
分析:离线树状数组,在线主席树(待写);
代码:
#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <algorithm>#include <climits>#include <cstring>#include <string>#include <set>#include <map>#include <queue>#include <stack>#include <vector>#include <list>#define rep(i,m,n) for(i=m;i<=n;i++)#define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++)#define mod 1000000007#define inf 0x3f3f3f3f#define vi vector<int>#define pb push_back#define mp make_pair#define fi first#define se second#define ll long long#define pi acos(-1.0)#define pii pair<int,int>#define Lson L, mid, rt<<1#define Rson mid+1, R, rt<<1|1const int maxn=1e6+10;using namespace std;ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);}ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}return f;}inline ll read(){    ll x=0;int f=1;char ch=getchar();    while(ch<0||ch>9){if(ch==-)f=-1;ch=getchar();}    while(ch>=0&&ch<=9){x=x*10+ch-0;ch=getchar();}    return x*f;}int n,m,k,t,pos[maxn],a[maxn],b[maxn],ans[maxn];vector<pii >query[maxn];void add(int x,int y){    for(int i=x;i<=n;i+=(i&(-i)))        a[i]+=y;}int get(int x){    int ret=0;    for(int i=x;i;i-=(i&(-i)))        ret+=a[i];    return ret;}int main(){    int i,j;    scanf("%d",&n);    rep(i,1,n)scanf("%d",&b[i]);    scanf("%d",&m);    rep(i,1,m)    {        int c,d;        scanf("%d%d",&c,&d);        query[d].pb(mp(c,i));    }    rep(i,1,n)    {        if(pos[b[i]])add(pos[b[i]],-1);        pos[b[i]]=i;        add(pos[b[i]],1);        for(pii x:query[i])ans[x.se]=get(i)-get(x.fi-1);    }    rep(i,1,m)printf("%d\n",ans[i]);    //system("Pause");    return 0;}

SPOJ DQUERY - D-query