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]是历史时刻的线段树, 后面的数还没有建进去。 */
本文介绍如何使用主席树解决区间内不同元素数量的问题。通过动态建立线段树并更新节点状态,实现高效查询指定区间内的不重复元素个数。
391

被折叠的 条评论
为什么被折叠?



