SPOJ 3267. D-query (主席树,查询区间有多少个不相同的数)

时间:2022-04-10 23:18:54

3267. D-query

Problem code: DQUERY

English Vietnamese

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

主席树的入门题了

 /* ***********************************************
Author :kuangbin
Created Time :2013-9-5 23:54:37
File Name :F:\2013ACM练习\专题学习\主席树\SPOJ_DQUERY.cpp
************************************************ */ #include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std; /*
* 给出一个序列,查询区间内有多少个不相同的数
*/
const int MAXN = ;
const int M = MAXN * ;
int n,q,tot;
int a[MAXN];
int T[M],lson[M],rson[M],c[M];
int build(int l,int r)
{
int root = tot++;
c[root] = ;
if(l != r)
{
int mid = (l+r)>>;
lson[root] = build(l,mid);
rson[root] = build(mid+,r);
}
return root;
}
int update(int root,int pos,int val)
{
int newroot = tot++, tmp = newroot;
c[newroot] = c[root] + val;
int l = , r = n;
while(l < r)
{
int mid = (l+r)>>;
if(pos <= mid)
{
lson[newroot] = tot++; rson[newroot] = rson[root];
newroot = lson[newroot]; root = lson[root];
r = mid;
}
else
{
rson[newroot] = tot++; lson[newroot] = lson[root];
newroot = rson[newroot]; root = rson[root];
l = mid+;
}
c[newroot] = c[root] + val;
}
return tmp;
}
int query(int root,int pos)
{
int ret = ;
int l = , r = n;
while(pos < r)
{
int mid = (l+r)>>;
if(pos <= mid)
{
r = mid;
root = lson[root];
}
else
{
ret += c[lson[root]];
root = rson[root];
l = mid+;
}
}
return ret + c[root];
} int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(scanf("%d",&n) == )
{
tot = ;
for(int i = ;i <= n;i++)
scanf("%d",&a[i]);
T[n+] = build(,n);
map<int,int>mp;
for(int i = n;i>= ;i--)
{
if(mp.find(a[i]) == mp.end())
{
T[i] = update(T[i+],i,);
}
else
{
int tmp = update(T[i+],mp[a[i]],-);
T[i] = update(tmp,i,);
}
mp[a[i]] = i;
}
scanf("%d",&q);
while(q--)
{
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",query(T[l],r));
}
}
return ;
}