P10814 【模板】离线二维数点
· 阅读需 2 分钟
题意简述
给定长度为 的序列 ,有 次询问。
每次询问给定 ,求区间 中满足 的元素数量。
解题思路
思想
每个元素 可以看作二维平面中的一个点 。
每次询问 等价于统计矩形 内点的数量。
直接二维数据结构会超时,考虑转化为可以 前缀查询 的一维问题。
差分
每次询问是可差分的,区间 可以拆分为 。
这样每次询问转化为 个 前缀询问 :统计区间 中满足 的元素数量。
统计
将所有 个前缀询问按第一维 排序。
用序列 维护值域, 表示当前第二维为 的元素数量。
对于每个前缀询问 ,先将所有 的 加入序列 ,得到前缀 的状态。
计算 表示当前满足 的元素数量,最后将 贡献到对应问题的答案。
使用 树状数组 维护序列 ,实现 单点修改和区间查询。
参考代码
#include <bits/stdc++.h>
using namespace std;
const int N=2000005;
int a[N],c[N],ans[N];
void add(int u){while(u<N){c[u]++;u+=u&-u;}}
int sum(int u){int res=0;while(u){res+=c[u];u-=u&-u;}return res;}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)cin>>a[i];
vector<tuple<int,int,int,int>> s;
for(int i=1;i<=m;i++)
{
int l,r,x;
cin>>l>>r>>x;
s.push_back({r,x,i,1});
s.push_back({l-1,x,i,-1});
}
sort(s.begin(),s.end());
int j=1;
for(auto [u,x,i,f]:s)
{
while(j<=u)add(a[j++]);
ans[i]+=sum(x)*f;
}
for(int i=1;i<=m;i++)cout<<ans[i]<<'\n';
return 0;
}
