离散化的本质就是映射,但是我们为什么需要映射来做呢?有时候,给我们的数据值域很大(10^9),但是数字个数却不是很大(10 ^5),但是这些数据并不是连续的,中间有很多空的地方(0),如果把这些0加上,我们想要开辟一个数组是根本无法达到的。(好像静态全局数组最大能开10 ^7),这时候我们就需要利用离散化,把这些有用的数据映射到一个新的数组上。
步骤:
- a[]中可能有重复的元素——去重
- 如何算出x离散化后的值——二分
例题:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 300010;//为什么开30万的空间->最后我们存在数组里面的数有①对n个x数进行+c ②输入左右区间l,r -> n + 2m
int n, m;//n表示对x进行+c的数据有n个,m表示求左右区间的操作有m次
int a[N], s[N];//数组a表示映射后的数组,数组s表示映射后的数组a的前缀和
vector<int> alls;//alls容器表示的就是原来的数组,这个数组的每个位置的值都是0
vector<PII> add, query;//add表示对x位置的数进行+c的操作,query表示存左右区间,他们都是要存两个数据的,所以都需要使用pair对组
//返回映射后的坐标
//有序的,所以我们可以使用二分
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;//返回 r+1 是为了让返回的数组下标是从1开始的 -> 方便计算前缀和
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; ++i)
{
int x, c;//x表示元素组的位置,c表示要在x位置上要加的数
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());//1.先排好序
alls.erase(unique(alls.begin(), alls.end()), alls.end());//unique函数表示把一段区间不重复的排在前面,重复的元素排在后面,返回的是重复元素的第一个的位置
//处理插入
for(auto item : add)//相当于遍历add->for(vector[HTML_REMOVED]::iterator it = add.begin(); it != add.end(); it ++)
{
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;
}