离散化
把整型区间的数映射到十万左右
1.去重
2.二分查找
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 3e5+7;
typedef pair<int, int> PII;
vector<PII> add, query; //添加的值 和查询的区间
vector<int> alls; //所有的坐标点
int a[N], s[N]; //原数组和前缀和数组
int n, m;
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 l+1; //从1开始映射
}
int main(){
cin>>n>>m;
int x, c;
for(int i = 0; i < n; i++){
cin>>x>>c;
add.push_back({x,c});
alls.push_back(x); //先把下标放入向量中 统一离散化
}
int u, v;
for(int i = 0; i < m; i++){
cin>>u>>v;
query.push_back({u, v});
alls.push_back(u);
alls.push_back(v);
}
//排序去重
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());
//离散化
for(auto item: add){ //先对添加里的元素映射 赋值
x = item.first, c = item.second;
a[find(x)] += c; //找到x的映射值 往原数组中加c
}
//求前缀和
for(int i = 1; i <= alls.size(); i++){ //总的元素
s[i] = s[i-1] + a[i];
}
for(auto item: query){
u = item.first, v = item.second;
cout<<s[find(v)] - s[find(u)-1]<<endl;
}
return 0;
}