1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include <cstdio> #include <map> #include <algorithm> #include <iostream> #include <stdio.h> #include <string> using namespace std; const int N = 3e4 + 5;
struct node{ int ls, rs, sum; }tree[4000005]; const int maxn = 30005; int a[maxn], rt[maxn]; int tot = 0; void build(int &o, int l, int r) { o = ++tot; tree[o].sum = 0; if(l == r) return; int mid = (l + r) >> 1; build(tree[o].ls, l , mid); build(tree[o].rs, mid + 1, r); }
void update(int &o , int last, int l, int r, int pos, int add) { o = ++tot; tree[o].ls = tree[last].ls; tree[o].rs = tree[last].rs; tree[o].sum = tree[last].sum + add; if(l == r) return; int mid = (l + r) >> 1; if(pos <= mid) update(tree[o].ls, tree[last].ls, l, mid, pos, add); else update(tree[o].rs, tree[last].rs, mid + 1, r, pos , add); } int sum; void query(int o, int l, int r, int left, int right) { if(left > r || right < l) return; if(left <= l && right >= r) { sum += tree[o].sum; return; } int mid = (l + r ) >> 1; query(tree[o].ls, l, mid, left, right); query(tree[o].rs, mid + 1, r, left, right); } int main() { int n,Q,l,r; scanf("%d",&n); for(int i = 1; i <= n; ++i) { scanf("%d",&a[i]); } scanf("%d",&Q); build(rt[0], 1, n); map<int,int>M; for(int i = 1; i <= n; ++i) { if(!M[a[i]]) { update(rt[i], rt[i - 1], 1, n, i, 1); } else{ int temp; update(rt[i], rt[i - 1], 1, n, M[a[i]], -1); update(rt[i], rt[i], 1, n, i, 1); } M[a[i]] = i; } while(Q--) { sum = 0; scanf("%d %d",&l, &r); query(rt[r], 1, n, l , r); cout << sum << '\n'; } }
|