AcWing 802. 区间和
原题链接
简单
作者:
我要出去乱说
,
2021-02-19 14:37:09
,
所有人可见
,
阅读 262
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 3e6 + 10; //取决于alls中元素个数,最多为3e5
vector<int> alls; //储存有值的下标和询问的下标
vector<PII> add, query; //add储存键值对(下标, 值),query储存询问区间
int a[N], s[N];
int n, m;
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 l + 1; //后边要求前缀和,坐标从1开始,所以加1
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) { //读入数据
int x, c; //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); //找到add在alls中映射的坐标
a[x] += item.second;
}
//求前缀和,按例中此时 alls = [1,3,4,6,7,8]
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;
}