------------恢复内容开始------------
HH有一串由各种漂亮的贝壳组成的项链。HH相信不同的贝壳会带来好运,所以每次散步 完后,他都会随意取出一
段贝壳,思考它们所表达的含义。HH不断地收集新的贝壳,因此他的项链变得越来越长。有一天,他突然提出了一
个问题:某一段贝壳中,包含了多少种不同的贝壳?这个问题很难回答。。。因为项链实在是太长了。于是,他只
好求助睿智的你,来解决这个问题。
Input
第一行:一个整数N,表示项链的长度。
第二行:N个整数,表示依次表示项链中贝壳的编号(编号为0到1000000之间的整数)。
第三行:一个整数M,表示HH询问的个数。
接下来M行:每行两个整数,L和R(1 ≤ L ≤ R ≤ N),表示询问的区间。
N ≤ 50000,M ≤ 200000。
Output
M行,每行一个整数,依次表示询问对应的答案。
Sample Input6 1 2 3 4 3 5 3 1 2 3 5 2 6Sample Output2 2 4
思路:离线操作,将r排序,利用树状数组快速求和,维护一个pre数组,在i加入时,pre[i]就要减1
#define lowbit(x) ((x)&(-x)) typedef long long LL; const int maxm = 1e6+5; const int maxn = 5e4+5; int C[maxn], pre[maxm], N, M, a[maxn], ans[200005]; struct Node { int l, r, id; bool operator<(const Node &t)const { return r < t.r; } }query[200005]; void add(int x, int val) { for(; x <= N; x += lowbit(x)) C[x] += val; } int getsum(int x) { int ret = 0; for(; x; x -= lowbit(x)) ret += C[x]; return ret; } int main() { scanf("%d", &N); for(int i = 1; i <= N; ++i) scanf("%d", &a[i]); scanf("%d", &M); for(int i = 0; i < M; ++i) { scanf("%d%d", &query[i].l, &query[i].r); query[i].id=i; } sort(query, query+M); int k = 1; for(int i = 0; i < M; ++i) { int j = query[i].r; for(; k <= j; ++k) { if(pre[a[k]]) add(pre[a[k]], -1); add(k, 1); pre[a[k]] = k; } ans[query[i].id] = getsum(j) - getsum(query[i].l-1); } for(int i = 0; i < M; ++i) printf("%d ", ans[i]); return 0; }
------------恢复内容结束------------