1. 程式人生 > >主席樹求區間distinct num

主席樹求區間distinct num

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x)&(-x))
typedef long long ll;
const int maxn = 1e5+5;
const int mod = 1e9+9;
int Case = 1, n, m;
int root[maxn], tot;
struct node{
	int l, r;
	int sum;
}tr[maxn<<8];
void build(int l, int r, int &
x) { x = ++tot; if(l == r) return ; int mid = (l+r)/2; build(l, mid, tr[x].l); build(mid+1, r, tr[x].r); } void update(int l, int r, int &x, int y, int pos, int c) { x = ++tot; tr[x] = tr[y]; tr[x].sum += c; if(l == r) return; int mid = (l+r)/2; if(pos<=mid) update(l, mid, tr[x].l, tr[
y].l, pos ,c); else update(mid+1, r, tr[x].r, tr[y].r, pos, c); } int query(int l, int r, int x, int pos) { if(l==r) return tr[x].sum; int mid = (l+r)/2; if(mid>=pos) return tr[tr[x].r].sum+query(l, mid, tr[x].l, pos); else return query(mid+1, r, tr[x].r, pos); } void solve() { scanf("%d"
, &n);tot = 0; map<int, int>last; build(1, n, root[0]); for(int i = 1; i <= n; i++) { int x, temp;scanf("%d", &x); if(!last[x]) update(1, n, root[i], root[i-1], i, 1); else update(1, n, temp, root[i-1], last[x], -1), update(1, n, root[i], temp, i, 1); last[x] = i; } scanf("%d", &m); for(int i = 1; i <= m; i++) { int l, r;scanf("%d%d", &l, &r); printf("%d\n", query(1, n, root[r], l)); } return; } int main() { //ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("/Users/hannibal_lecter/Desktop/code/in.txt", "r", stdin); //freopen("/Users/hannibal_lecter/Desktop/code/out.txt","w",stdout); #endif scanf("%d", &Case); while(Case--) { solve(); } return 0; }