离散化
有一个这样的数轴,我们在上面取n个数(1<=n<=1e6)分别为a[1~n];
数组a的范围是数轴的长度
求我们查询某个点到另一个点区间内的值的和
在一个长度这么大的数轴上查找某个点肯定不可以遍历的查找方法,首先我们想到的就是数轴的位置作为下标,将前缀和存储在数组里,直接通过下标找到我们想要的值,然后通过两个下标用前缀和的方式来得到区间内的值。
(前缀和可以去翻阅其他的博客来了解一下)
但是由于我们的数值范围过大,需要2*1e9个数组来存储我们的下标对应的前缀和的值,这个方法就不可行了,于是我们采用离散化的操作来使得我们能够在更小的空间内实现这样的计算
离散化的操作分为三部,排序,去重,然后映射,通过数值的大小关系放进数组内,
这样子我们只需要两个长度在n的范围内的数组就可以表示左右的值了
第一个数组用来查找对应数所在的数组下标,通过数组下标映射关系,在第二个数组内进行运算,查找数组下标我们用二分法查找。
如果我们要查265415在哪里
二分法找到265415在1数组的下标为7的位置,然后让2数组的7号位置进行运算就可以了
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 300010;
int a[N], s[N];
int n, m;
vector<int> alls;
vector<PII> add, query;
int find(int x)
{
int l = 0, r = alls.size() - 1;
while(l < r)
{
int mid = l + r >> 1;
if(alls[mid] >= x) r = mid;
else l = mid + 1;
}
return r + 1;
}
vector<int>:: iterator unique(vector<int> &a)
{
int j = 0;
for(int i = 0; i < a.size(); i ++)
if(!i || a[i] != a[i - 1])
a[j ++ ] = a[i];
return a.begin() + j;
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; i ++ )
{
int x, c;
cin >> x >> c;
add.push_back({x, c});
alls.push_back(x);
}
for(int i = 0; i < m; i ++ )
{
int l, r;
cin >> l >> r;
query.push_back({l, r});
alls.push_back(l);
alls.push_back(r);
}
sort(alls.begin(), alls.end());
alls.erase(unique(alls), alls.end());
for(auto item : add)
{
int x = find(item.first);
a[x] += item.second;
}
for(int i = 1; i <= alls.size(); i ++ ) s[i] = s[i - 1] + a[i];
for(auto item : query)
{
int l = find(item.first), r = find(item.second);
cout << s[r] - s[l - 1] << endl;
}
return 0;
}
离散化模板
vector<int> alls; // 存储所有待离散化的值
sort(alls.begin(), alls.end()); // 将所有值排序
alls.erase(unique(alls.begin(), alls.end()), alls.end()); // 去掉重复元素
数组下标对应映射关系,当需要对离散化后的数组进行操作时,对原数组的数组下标也需要进行离散化
// 二分求出x对应的离散化的值
int find(int x) // 找到第一个大于等于x的数组位置
{
int l = 0, r = alls.size() - 1;
while (l < r)
{
int mid = l + r >> 1;
if (alls[mid] >= x) r = mid;
else l = mid + 1;
}
return r + 1; // 映射到下标1, 2, ...n
}
**南昌理工acm集训队**