离散化,将一个无限长的数组,里面的有数的位置,建立一个映射,即把所有用到的数,建立成一个从1开始的数组就可以了 ,这里输入n个加入的数的下标以及m对左右区间,共n + 2 * m <= 3 * 105 个坐标,故最后坐标的区间范围小于3 * 105个,可以作为新数组坐标的数组范围。
假设原来用到的下标是1, 2, 100, 2000, 30000, 将之映射到新的下标即可。
做好了映射之后,开始对相应的映射组成一个新的数组a[N],并对之进行前缀和操作:
-
先将所有需要操作的代码下标写进一个数组里,上面的x和要操作的区间l, r
-
对这些区间重复的原下标进行去重
-
用二分法find找到对应的新区间下标 (return r + 1)已经进行了加一处理(下面的二分法是可以用lower_bound()函数直接替代的)
int find (int x) {
return lower_bound(alls.begin(), alls.end(), x) - alls.begin() + 1
}
// lower_bound()返回值是一个迭代器,所以减去begin()得到相对位置,加一 和 r + 1 一个效果
-
新数组插入数据,用二分找出对应下标
-
求新数组a[N]的前缀和s[N]
-
用二分find找到(l, r)新下表输出
code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
const int N = 3 * 1e5 + 10;
int n ,m;
int a[N], s[N];
vector<int>alls;
vector<PII> add, query;
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;
}
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), c = item.second;
a[x] += c;
}
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;
}