题目链接:[spoj D-query]
题意描述:给定 N 个数 a1,a2,…,an , Q 个询问。每次查询求区间中不同数的个数。 (1≤N≤30000,1≤Q≤200000,1≤ai≤106,)
解题思路:用第 i 线段树来维护前 i 个数,从第 j 个数到第 i 个数的区间不同数 (∀j,1≤j≤i) 。那么根据第 i 棵树以及 ai+1 ,求第 i+1 棵树的步骤如下:
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
#define fst first
#define snd second
#define __mid__ int mid = ((l + r) >> 1)
//typedef __int64 LL;
//typedef unsigned __int64 ULL;
typedef pair<int, int> PII;
const int MAXN = 30000 + 5;
const int MX = 1e6 + 5;
const int INF = 0x3f3f3f3f;
int N, Q, A[MAXN], L, R;
int TSZ;
int root[MAXN];
int rec[MX];
struct TNode {
int ls, rs, sum;
} node[MAXN * 20];
int build(int l, int r) {
int rt = TSZ ++;
node[rt].sum = 0;
if(l == r) { node[rt].ls = node[rt].rs = -1; return rt; }
__mid__;
node[rt].ls = build(l, mid);
node[rt].rs = build(mid + 1, r);
return rt;
}
int update(int pos, int v, int r1, int l, int r) {
int r2 = TSZ ++;
node[r2] = node[r1];
node[r2].sum += v;
if(l == r) return r2;
__mid__;
if(pos <= mid) node[r2].ls = update(pos, v, node[r1].ls, l, mid);
else node[r2].rs = update(pos, v, node[r1].rs, mid + 1, r);
return r2;
}
int query(int pos, int rt, int l, int r) {
if(l == r) return node[rt].sum;
__mid__;
if(pos <= mid)
return query(pos, node[rt].ls, l, mid) + node[node[rt].rs].sum;
else return query(pos, node[rt].rs, mid + 1, r);
}
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
while(~scanf("%d", &N)) {
for(int i = 1; i <= N; i++) scanf("%d", &A[i]);
TSZ = 0;
memset(rec, -1, sizeof(rec));
root[0] = build(1, N);
for(int i = 1; i <= N; i++) {
int& x = A[i];
if(rec[x] == -1) {
root[i] = update(i, 1, root[i - 1], 1, N);
} else {
int temp = update(rec[x], -1, root[i - 1], 1, N);
root[i] = update(i, 1, temp, 1, N);
}
rec[x] = i;
}
scanf("%d", &Q);
while(Q --) {
scanf("%d %d", &L, &R);
int ans = query(L, root[R], 1, N);
printf("%d\n", ans);
}
}
return 0;
}