acwing802.区间和
即:数据十分稀疏。
离散化就是一个映射的过程,将数据变得紧凑,便于处理。
模板如下
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
}
作者:yxc
链接:https://www.acwing.com/blog/content/277/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1.读入数据:注意要把查询区间的端点也读入alls中,不然查询的时候找不到这些点
2.排序去重:因为要进行二分查找所以排序,因为可能会存在重复的端点,但是有的端点是没有值的,这会影响接下来求前缀和,因此要去重。
3.处理添加:a数组是映射数组,下标就是原数组映射过来的值+1(为了便于处理前缀和),a数组的值就是对应原数组的值
4.处理询问:利用find函数找到询问端点在映射数组中的下标,然后再利用前缀和即可!
#include <iostream>
#include <algorithm>
#include <vector>
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;
//二分查找大于等于x的数中最小的那个
int find(int x)
{
int l = 0 , r = alls.size() - 1;
while(l < r)
{
int mid = l + r >> 1;
if(x <= alls[mid]) r = mid;
else l = mid + 1;
}
return r + 1;
}
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.begin() , alls.end()) , 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;
}
}