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

Input
5
1 1 2 1 3
3
1 5
2 4
3 5

Output
3
2
3 
#include <bits/stdc++.h>
using namespace std;
const int maxn = 30003;
int a[maxn], rt[maxn], tot, last[1000004];
struct tree{
	int lson, rson, sz;
}c[maxn << 5];
int build(int o, int l, int r){
	int id = ++tot;
	c[id].sz = 0;
	if(l == r) return id;
	int mid = l + r >> 1;
	c[id].lson = build(o << 1, l, mid);
	c[id].rson = build(o << 1 | 1, mid + 1, r);
	return id;
}
int add(int pre, int pos, int l, int r, int v){
	int id = ++tot;
	c[id].sz = c[pre].sz + v;
	c[id].lson = c[pre].lson;
	c[id].rson = c[pre].rson;
	if(l == r) return id;
	int mid = l + r >> 1;
	if(pos <= mid) c[id].lson = add(c[id].lson, pos, l, mid, v);
	else c[id].rson = add(c[id].rson, pos, mid + 1, r, v);
	return id;
}
int query(int rt, int pos, int l, int r){
	if(l == r) return c[rt].sz;
	int mid = l + r >> 1;
	if(pos <= mid) return c[c[rt].rson].sz + query(c[rt].lson, pos, l, mid);
	else return query(c[rt].rson, pos, mid + 1, r);
}
int main(){
	int n, q, l, r, tmp;
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i){
		scanf("%d", &a[i]);
	}
	tot = 0;
	rt[0] = build(1, 1, n);
	memset(last, 0, sizeof(last));
	for(int i = 1; i <= n; ++i){
		if(last[a[i]] == 0){
			rt[i] = add(rt[i - 1], i, 1, n, 1);
		}
		else{
			tmp = add(rt[i - 1], last[a[i]], 1, n, -1);
			rt[i] = add(tmp, i, 1, n, 1);
		}
		last[a[i]] = i;
	}
	scanf("%d", &q);
	while(q--){
		scanf("%d %d", &l, &r);
		printf("%d\n", query(rt[r], l, 1, n));
	}
}


/*
题意:
30000个数,问区间有多少个不同的数。

思路:
主席树 入门题。按原数组下标动态开点建线段树,之前出现过的数先删掉,然后再加进去,然后对于区间[l,r],
不同数的个数就是rt[r]中下标在l后面的区间中数的个数。这里r后面的数不会算进去因为rt[r]是历史时刻的线段树,
后面的数还没有建进去。
*/


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值