HH的项链
★★★ 输入文件:diff.in
输出文件:
diff.out
简单对比
时间限制:1 s 内存限制:256 MB
问题描述:
HH有一串由各种漂亮的贝壳组成的项链。HH相信不同的贝壳会带来好运,所以每次散步
完后,他都会随意取出一段贝壳,思考它们所表达的含义。HH不断地收集新的贝壳,因此,
他的项链变得越来越长。有一天,他突然提出了一个问题:某一段贝壳中,包含了多少种不同
的贝壳?这个问题很难回答。。。因为项链实在是太长了。于是,他只好求助睿智的你,来解
决这个问题。
输入格式:
第一行:一个整数N,表示项链的长度。
第二行:N个整数,表示依次表示项链中贝壳的编号(编号为0到1000000之间的整数)。
第三行:一个整数M,表示HH询问的个数。
接下来M行:每行两个整数,L和R(1 ≤ L ≤ R ≤ N),表示询问的区间。
输出格式:
M行,每行一个整数,依次表示询问对应的答案。
样例输入:
6
1 2 3 4 3 5
3
1 2
3 5
2 6
样例输出:
2
2
4
数据范围:
对于20%的数据,N ≤ 100,M ≤ 1000;
对于40%的数据,N ≤ 3000,M ≤ 200000;
对于100%的数据,N ≤ 50000,M ≤ 200000。
#include <map>
#include <set>
#include <list>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <vector>
#include <bitset>
#include <cstdio>
#include <string>
#include <numeric>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
int dx[4]= {-1,1,0,0};
int dy[4]= {0,0,-1,1}; //up down left right
bool inmap(int x,int y,int n,int m)
{
if(x<1||x>n||y<1||y>m)return false;
return true;
}
int hashmap(int x,int y,int m)
{
return (x-1)*m+y;
}
#define eps 1e-8
#define inf 0x7fffffff
#define debug puts("BUG")
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define read freopen("diff.in","r",stdin)
#define write freopen("diff.out","w",stdout)
#define maxn 1000001
#define lowbit(x) (-x)&x
/**
把询问按右端点排序,
从前到后,对于每个颜色,
在它上一次出现的地方的后一点+1,
在当前位置的后一点-1;
当前询问答案为ΣXi(1..L)
**/
const int N=1000002;
int n,m;
struct rec
{
int n,x,y;
} a[N];
int color[N],last[N],pre[N],ans[N];
int c[N];
bool cmp(rec a,rec b)
{
return a.y<b.y;
}
void inc(int x,int w)//树状数组
{
while(x<=n)
{
c[x]+=w;
x+=lowbit(x);
}
}
int sum(int x)//树状数组
{
int s=0;
while(x>0)
{
s+=c[x];
x-=lowbit(x);
}
return s;
}
int main()
{
read;
write;
scanf("%d",&n);
for(int i=1; i<=n; ++i)
{
scanf("%d",color+i);
pre[i]=last[color[i]];//记录当前颜色前一次出现的位置
last[color[i]]=i;//修改当前颜色最后一次出现的位置
}
scanf("%d",&m);
for(int i=0; i<m; ++i)
{
scanf("%d%d",&a[i].x,&a[i].y);
a[i].n=i;
}
sort(a,a+m,cmp);//排序
int now=0;
for(int i=0; i<m; ++i)
{
while(now<a[i].y)//插入颜色
inc(pre[++now]+1,1),inc(now+1,-1);
ans[a[i].n]=sum(a[i].x);
}
for(int i=0; i<m; ++i)
printf("%d\n",ans[i]);
return 0;
}