离散化算法的思想是将一组连续的数据映射到一组离散的取值,通常是整数。它的主要目的是将连续的数据转换为离散的数据,以便进行统计、计数、排序等操作。
C++代码实现:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 300000;
int n, m;
int a[N]; // 存储每个离散化后的值对应的增量
int s[N]; // 存储前缀和数组
vector<int> alls; // 存储所有需要离散化的值
vector<pair<int,int>> add, query; // 存储输入的add和query数组
// 二分查找函数,用于找到x在alls中的位置
int find(int x){
int l = 0; // 左边界
int r = alls.size() - 1; // 右边界
while(l < r){
int mid = l + r >> 1; // 计算中间位置
if(alls[mid] >= x){ // 如果中间位置的值大于等于x
r = mid; // 更新右边界
}
else{
l = mid + 1; // 更新左边界
}
}
return r + 1; // 返回x在alls中的位置
}
int main(){
// 读取n和m的值
cin >> n >> m;
// 读取add数组的值
for(int i = 0; i < n; i++){
int x, c;
cin >> x >> c;
add.push_back({x, c}); // 将x和c作为一对加入add数组
alls.push_back(x); // 将x加入alls数组
}
// 读取query数组的值
for(int i = 0; i < m; i++){
int l, r;
cin >> l >> r;
query.push_back({l, r}); // 将l和r作为一对加入query数组
alls.push_back(l); // 将l加入alls数组
alls.push_back(r); // 将r加入alls数组
}
// 对alls进行排序并去重
sort(alls.begin(), alls.end()); // 对alls数组进行升序排序
alls.erase(unique(alls.begin(), alls.end()), alls.end()); // 去除alls数组中的重复元素
// 根据add数组更新a数组
for(auto item : add){
int x = find(item.first); // 找到item.first在alls中的位置
a[x] += item.second; // 将item.second加到a[x]上
}
// 计算前缀和数组s
for(int i = 1; i <= alls.size(); i++){
s[i] = s[i - 1] + a[i]; // 计算前缀和
}
// 根据query数组输出结果
for(auto item : query){
int l = find(item.first); // 找到item.first在alls中的位置
int r = find(item.second); // 找到item.second在alls中的位置
cout << s[r] - s[l - 1] << endl; // 输出结果
}
return 0;
}