DQUERY - D-query
English | Vietnamese |
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]是歷史時刻的線段樹,
後面的數還沒有建進去。
*/