离散化本质上可以看作一种哈希,离散化操作之后,可以保证一组数据在经过处理之后,其相对位置并没有发生变化。
即:当给出的数据自身,因为过大或者类型无法匹配无法作为数组下标,且影响最终结果的只有数据间的相对大小关系时,我们可以将原来的数据按照从大到小编号来处理问题,即离散化。
用来离散化的可以是大整数、浮点数、字符串等等。
例题:Acwing802.区间和
假定有一个无限长的数轴,数轴上每个坐标上的数都是 0。
现在,我们首先进行 n 次操作,每次操作将某一位置 x 上的数加 c。
接下来,进行 m 次询问,每个询问包含两个整数 l 和 r,你需要求出在区间 [l,r] 之间的所有数的和。
输入格式
第一行包含两个整数 n 和 m。
接下来 n 行,每行包含两个整数 x 和 c。
再接下来 m 行,每行包含两个整数 l 和 r。
输出格式
共 m 行,每行输出一个询问中所求的区间内数字和。
数据范围
−10^9 ≤ x ≤ 10^9,
1 ≤ n,m ≤ 105,
−10^9 ≤ l ≤ r ≤ 10^9,
−10000 ≤ c ≤ 10000
输入样例:
3 3
1 2
3 6
7 5
1 3
4 6
7 8
输出样例:
8
0
5
题解:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair<int,int> PII;
const int N = 1e6+10;
vector<int> alls;//存储出现过的所有下标
vector<PII> add,query;//分别存储对应的操作
int a[N],s[N];//a为映射数组,s为前缀和数组
int main()
{
int n,m;
int x,c,l,r;
cin>>n>>m;
for(int i = 1; i <= n;i++)
{
cin>>x>>c;
add.push_back({x,c});
alls.push_back(x);
}
for(int i = 1; i <= m;i++)
{
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.begin(),alls.end()),alls.end());//对下标进行去重
for(auto it : add)
{
x = lower_bound(alls.begin(),alls.end(),it.first) - alls.begin() + 1;//获取下标从1 开始的映射下标
a[x] += it.second;
}
for(int i = 1 ;i <= alls.size();i++)
{
s[i] = s[i - 1] + a[i];//处理前缀和
}
for(auto it : query)
{
l = lower_bound(alls.begin(),alls.end(),it.first) - alls.begin() + 1;
r = lower_bound(alls.begin(),alls.end(),it.second) - alls.begin() + 1;//获取下标从1 开始的映射下标
cout<<s[r] - s[l - 1]<<endl;//输出区间和
}
}