题目大意
Description
HH有一串由各种漂亮的贝壳组成的项链。HH相信不同的贝壳会带来好运,所以每次散步 完后,他都会随意取出一段贝壳,思考它们所表达的含义。HH不断地收集新的贝壳,因此, 他的项链变得越来越长。有一天,他突然提出了一个问题:某一段贝壳中,包含了多少种不同 的贝壳?这个问题很难回答。。。因为项链实在是太长了。于是,他只好求助睿智的你,来解 决这个问题。
第一行:一个整数N,表示项链的长度。 第二行:N个整数,表示依次表示项链中贝壳的编号(编号为0到1000000之间的整数)。 第三行:一个整数M,表示HH询问的个数。 接下来M行:每行两个整数,L和R(1 ≤ L ≤ R ≤ N),表示询问的区间。
Output
M行,每行一个整数,依次表示询问对应的答案。
6 1 2 3 4 3 5 3 1 2 3 5 2 6
Sample Output
2 2 4
HINT
对于20%的数据,N ≤ 100,M ≤ 1000; 对于40%的数据,N ≤ 3000,M ≤ 200000; 对于100%的数据,N ≤ 50000,M ≤ 200000。
Source
Day2
分析
这是一个经典问题,询问区间内不同数字的个数。
考虑单个询问,扫描在右端点左边的数字。对于每一个数字,我们只需要将1~他最后出现的位置之间进行区间加一,最后我们只需要求出在左端点那个位置的值即可。 这个可以用树状数组来解决。 我们将询问按照右端点排序。 然后对应每一个数字
ai
,我们预处理出
li
,即上一次出现与
ai
数值相等的位置+1。当我们扫描到一个数字时,我们只需要对
[li,i]
区间+1即可。在树状数组中的操作就是在
li
处+1,
i+1
处-1。
代码
#include<cstdio>
#include<algorithm>
#define MAXN 50000
#define MAXM 200000
#define MAXV 1000000
using namespace std;
int n,m,la[MAXV+
10],l[MAXN+
10],c[MAXN+
10],a[MAXN+
10],ans[MAXM+
10];
inline int lowbit(
int &x){
return x&-x;
}
void update(
int x,
int d){
while(x<=n){
c[x]+=d;
x+=lowbit(x);
}
}
int get_sum(
int x){
int ret(
0);
while(x){
ret+=c[x];
x^=lowbit(x);
}
return ret;
}
struct Query{
int l,r,pos;
bool operator < (
const Query &b)
const{
return r<b.r;
}
}q[MAXM+
10];
void Read(
int &x){
char c;
while(c=getchar(),c!=EOF)
if(c>=
'0'&&c<=
'9'){
x=c-
'0';
while(c=getchar(),c>=
'0'&&c<=
'9')
x=x*
10+c-
'0';
ungetc(c,stdin);
return;
}
}
void read(){
int i;
Read(n);
for(i=
1;i<=n;i++){
Read(a[i]);
l[i]=la[a[i]]+
1;
la[a[i]]=i;
}
Read(m);
for(i=
1;i<=m;i++)
Read(q[i].l),Read(q[i].r),q[i].pos=i;
}
void solve(){
sort(q+
1,q+m+
1);
int i,j;
for(j=i=
1;i<=m;i++){
while(j<=q[i].r){
update(l[j],
1);
update(++j,-
1);
}
ans[q[i].pos]=get_sum(q[i].l);
}
}
void print(){
for(
int i=
1;i<=m;i++)
printf(
"%d\n",ans[i]);
}
int main()
{
read();
solve();
print();
}
转载请注明原文地址: https://ju.6miu.com/read-1297087.html