AcWing 802. 区间和
原题链接
简单
作者:
kiiiim
,
2022-07-08 16:44:59
,
所有人可见
,
阅读 183
注意事项:
1.N的取值300010,l-r的n和m,2*100000 + 100000 + 10
2.alls里面存放的全是下标,其作用是为了处理前缀和。注意,全是下标!x也是下标,而不是一个数,处理前缀和所以需要去重。你查询到时候,可能是某一块没有数的区间所以也要存
3.有的解析说,离散化下标必须从1开始,其实是这题用到了前缀和
4.在query查询的时候,l和r也要用find函数来查找,即其已经被离散化。
整体思路:
1.首先将x与c(下标x的位置加上c)存放到add里,同时将下标x存放到alls
2.存放l和r到query中,同时将l和r存放到alls
3.去重,模版背下来就好了
4.为数组a存值
5.计算前缀和数组s
6.查询l-r之间的和
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 300010;
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);
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), r = find(item.second);
cout << s[r] - s[l - 1] << endl;
}
return 0;
}