Acwing 802. 区间和
题目描述
假定有一个无限长的数轴,数轴上每个坐标上的数都是 0。
现在,我们首先进行 n次操作,每次操作将某一位置 x 上的数加 c。
接下来,进行 m次询问,每个询问包含两个整数 l 和 r,你需要求出在区间 [l,r] 之间的所有数的和。
输入格式
第一行包含两个整数 n 和 m。
接下来 n行,每行包含两个整数 x 和 c。
再接下来 m行,每行包含两个整数 l 和 r。
输出格式
共 m 行,每行输出一个询问中所求的区间内数字和。
数据范围
−109≤x≤109,
1≤n,m≤105,
−109≤l≤r≤109,
−10000≤c≤10000
思路
类似于哈希,不过哈希是通过数学函数变幻映射,这里更简单,将所有出现的数对 插入的数 x 和 c,
用x映射,将去重和排序好的出现在数轴上的所有将第一个数序号记做1,第二个就是2 ,以此类推。find 函数就是寻找对于数组的序号,方便再a中索引。这样就是将原来的问题变成了前缀和问题。
为什么就变成了前缀和了呢?
因为我们将插入的数进行了记录,这样就可以得到对应在插入值的地方得到类似前缀和的数组a了。
接下来就是处理计算出和的大小然后放入s数组,但是这样如果查询没有插入过数字的地方就比较麻烦,需要进行查找,左右两边需要查找到边界为小于等于该数的最大数。我们可以将查询数看作该位置插入0就行了。这样就可以直接用前缀和计算了。
代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n ,m;
const int N = 300010;
int a[N] ,s[N];
typedef pair<int,int> PII;
vector<PII> add ,seq;
vector<int> alls;
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;
}
int main()
{
scanf("%d %d",&n,&m);
for(int i = 0 ;i < n ; ++ i)
{
int a ,x;
scanf("%d%d",&a,&x);
alls.push_back(a);
add.push_back({a,x});
}
while(m--)
{
int l,r;
scanf("%d%d",&l,&r);
alls.push_back(l);
alls.push_back(r);
seq.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 item : seq)
{
int l = find(item.first), r = find(item.second);
cout << s[r] - s[l - 1] << endl;
}
return 0;
}