#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
typedef pair<int, int> PII;
int n, m, l, r, x, c;
int a[N], s[N];
//所有输入的数据全部成对出现,使用二元组保存数据;
vector<PII> add, query;
vector<int> alls;
//find函数将多个不连续的数映射到一连串有序数上,同时使用二分模板;
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() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
while(n--){
cin >> x >> c;
add.push_back({x, c});
alls.push_back(x);
}
while(m--){
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 new_x = find(item.first);
a[new_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] << '\n';
}
return 0;
}
y总模板之区间和(离散化问题)
最新推荐文章于 2024-10-08 20:32:22 发布