AcWing 802. 区间和
原题链接
简单
作者:
HowardY
,
2022-01-15 15:30:43
,
所有人可见
,
阅读 197
在映射时注意是在alls中查找x的位置
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
const int N = 300010;
vector<int> alls;//储存所有待处理的数值/下标
vector<PII> add, query;
int a[N], s[N];//a是被映射的数组,从1开始的自然数
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;//在alls中找到x
else l = mid + 1;
}
return r + 1;
}
int main()
{
int n, m;
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);
int r = find (item.second);
int res = s[r] - s[l - 1];
printf("%d\n",res);
}
return 0;
}