会了这道题,感觉前缀和,差分,离散化都没什么问题了!!!
#include<iostream>
#include<algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 300010;
// 为什么是300000?1e5个位置,1e5次询问,每次两个下标,共3*1e5个
/*
离散化:重要!将大数映射到小数
*/
int n, m;
int a[N], s[N]; // a是映射后的数据
vector<int> alls; // 将要映射的下标
vector<PII> add, query; // 暂时保存处理请求和询问请求
// 映射函数,将区间离散的数映射到小区间连续的数
int find(int x)
{
// 将alls容器中的大数全映射到1~alls.size()连续的数
// 由于去过重,保证是单一映射
int l = 0, r = alls.size() - 1;
// 使用二分将大数x映射为alls容器中对应的下标+1。
while(l < r)
{
int mid = l + r + 1 >> 1;
if(alls[mid] > x) r = mid - 1;
else l = mid;
}
return l + 1; // 让a[]数组下标从1开始,方便前缀和计算
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; i ++ )
{
int x, c;
scanf("%d%d", &x, &c);
add.push_back({x, c});
alls.push_back(x);
}
while (m -- )
{
int l, r;
scanf("%d%d", &l, &r);
alls.push_back(l);
alls.push_back(r);
query.push_back({l, 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 q : query)
{
int l = find(q.first), r = find(q.second);
printf("%d\n", s[r] - s[l - 1]);
}
return 0;
}