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
题意
一个n个数的序列。
现在有q次查询,对于每次查询输出该区间的不同数字的个数
题解
由于只有查询操作,我们可以采用离线+树状数组来写这道题
我们需要知道的是为什么用离线
因为如果将所有的查询按照右端点排好序后,每个查询将不再是独立的,而是一个递推的关系。
我们可以从第一个元素开始,用vis[]数组记录每个元素出现的最后的位置
如果当前位置i的元素arr[i]没有出现,那么vis[arr[i]]=i,我们用树状数组将当前位置的权值加1,因为当前位置的元素贡献了1.
如果当前位置i的元素arr[i]已经出现过了,那么pre=vis[arr[i]]是arr[i]元素之前出现的位置。我们就将pre位置减去1,同时当前i位置加上1,并且更新vis[arr[i]].
为什么这么做可以?
因为对于当前位置来说,能对之后的查询起到贡献的一定是最靠后的元素。所以说排好序的查询之间存在依赖关系。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e4+10;
int arr[maxn];
int vis[1000010];
struct BIT
{
int c[maxn];
int lowbit(int x) {return x & -x;}
void init()
{
memset(c,0,sizeof(c));
}
void update(int pos,int val)
{
for(int i=pos;i<maxn;i+=lowbit(i)) c[i] += val;
return ;
}
int sum(int pos)
{
int ans = 0;
for(int i=pos;i>0;i-=lowbit(i)) ans += c[i];
return ans;
}
}bit;
struct Qu
{
int ql,qr,id;
};
bool cmp(const struct Qu &a,const struct Qu &b) {
return a.qr < b.qr;
}
Qu query[200010];
int ans[200010];
int main()
{
int n,q;
while(~scanf("%d",&n))
{
memset(vis,0,sizeof(vis));
bit.init();
for(int i=1;i<=n;i++) scanf("%d",&arr[i]);
scanf("%d",&q);
for(int i=1;i<=q;i++) {
scanf("%d%d",&query[i].ql,&query[i].qr);
query[i].id = i;
}
std::sort(query+1,query+1+q,cmp);
int cur = 1;
for(int i=1;i<=n;i++) {
if(vis[arr[i]] == 0) {
bit.update(i,1);
vis[arr[i]] = i;
}
else {
bit.update(vis[arr[i]],-1);
vis[arr[i]] = i;
bit.update(i,1);
}
// printf("%d %d\n",i,bit.sum(i));
while(cur<=q && query[cur].qr == i) {
ans[query[cur].id] = bit.sum(query[cur].qr) - bit.sum(query[cur].ql-1);
cur++;
}
}
for(int i=1;i<=q;i++) printf("%d\n",ans[i]);
}
return 0;
}