整数有序区间和的注意事项
区间和是离散化的运用到典例。所谓离散化,是一种缩小程序数据的方法,能够降低程序的时间复杂度。
先看例题:802. 区间和 - AcWing题库
这道题的完整代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 3e5 + 10;
int n, m;
typedef pair<int, int> PII;
vector<int>alls;
vector<PII> n_, m_;
int a[N], s[N];
int find(int a)
{
int l = 0, r = alls.size() - 1;
while (l < r)
{
int mid = l + r >> 1;
if (alls[mid] >= a) 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;
n_.push_back({ x,c });
alls.push_back(x);
}
for (int i = 0; i < m; i++)
{
int l, r;
cin >> l >> r;
m_.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 : n_)
{
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 : m_)
{
int l = find(item.first), r = find(item.second);
cout << s[r] - s[l - 1] << endl;
}
return 0;
}
下面来讲讲它的注意事项:
1、N的范围:
- N的范围主要由数组s决定, 由n和m两个循环可知,s的最大元素数为n+2m,由n和m最大值为1e5,所以N的最大值为3e5。
2、 在前缀和预处理前的去重:
- vector::erase()函数的作用是删除指定范围内的元素
- unique()函数的作用就是将重复的元素放到容器的后边,并返回到最后一个元素的地址。该函数是对相邻重复元素的处理,所以在调用之前要先对容器进行排序。
3、 前缀和的预处理:
- 前缀和预处理之后能够十分有效地降低时间复杂度,从l到r的每个元素相加,到r元素减去l-1元素,操作简单了许多。
4、 find函数的作用:
- find函数很明显是二分,作用是找到贮存在容器alls中对应坐标的下标。由于经过sort排序,因此可以通过二分对其进行操作。
- 由于前缀和预处理是从1开始的,所以返回值是r+1,这个应题目而异。